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;
}
相关推荐
安全系统学习1 小时前
网络安全逆向分析之rust逆向技巧
前端·算法·安全·web安全·网络安全·中间件
sz66cm1 小时前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先
陳麦冬2 小时前
深入理解指针(二)
c语言·学习
菜鸟懒懒2 小时前
exp1_code
算法
Winn~3 小时前
JVM垃圾回收器-ZGC
java·jvm·算法
爱coding的橙子3 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光3 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿3 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm3 小时前
leetcode78. 子集
算法·深度优先
岁忧3 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go