C语言双指针,leetcode: 盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0)(i, height[i])

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

**说明:**你不能倾斜容器。

示例 1:

复制代码
输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

复制代码
输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

算法:

暴力枚举:超时,时间复杂度是O(n^2)

cpp 复制代码
int min(int a,int b)
{
    if(a>b)
    return b;
    else
    return a;
}
int maxArea(int* height, int heightSize) {
    int volume;
    int maxvolume=0;
    int left,right;
    for(left=0;left<heightSize-1;left++){
        for(right=heightSize-1;right>left;right--){
            volume=min(*(height+left),*(height+right))*(right-left);
            if(volume>maxvolume){
            maxvolume=volume;
            }
        }
    }
    return maxvolume;
}

双指针扫描方法

特别是一种称为"夹逼法"或"双指针技巧"的方法。

因为容量最大,我们追去高度高和宽度宽,所以移动宽度时,牺牲高度矮的那个。

这里的主要思想是:

  1. 使用两个指针,一个指向数组的开始,另一个指向数组的末尾。
  2. 计算当前指针位置形成的容器的容量。
  3. 移动指向较短线段的指针,因为这样可能会找到更高的线段,从而可能获得更大的容量。

O(n)时间复杂度

cpp 复制代码
int maxArea(int* height, int heightSize) {
    int maxVolume = 0;
    int left = 0, right = heightSize - 1;
    
    while (left < right) {
        int h = height[left] < height[right] ? height[left] : height[right];
        int w = right - left;
        int volume = h * w;
        
        if (volume > maxVolume) {
            maxVolume = volume;
        }
        
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    
    return maxVolume;
}
相关推荐
春风解人意7 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
政企项目老覃9 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
是隼人10 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
淡海水10 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR10 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵10 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽10 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil20811 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
刃神太酷啦11 小时前
Redis 进阶核心:持久化 (RDB/AOF)、事务与主从复制全解析----《Hello Redis!》(5)
linux·c语言·数据库·c++·redis·缓存·bootstrap