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 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
戊本菌1 天前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
LK_071 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊1 天前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司1 天前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
嵌入式 Linux手记1 天前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式