zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Leetcode 11. 盛最多水的容器

LeetCode容器 11 最多水
2023-06-13 09:15:27 时间

算法:左右双指针。两端中的短边朝向另一端移动,直至双指针相遇。

时间复杂度:O(N)

我的C源码:

int maxArea(int* height, int heightSize){
    int max = 0;
    int left= 0;
    int right = heightSize-1;
    int a, b, area;
    while(left < right)
    {
        a = height[left];
        b = height[right];
        if (a <= b)
        {
            area = a * (right - left++);
        }
        else
            area = b * (right-- - left);
        if(area > max) max = area;
    }
    // for(int i =0; i< heightSize-1; i++) //暴力解法会超时
    // {
    //     for(int j= i+1; j< heightSize; j++)
    //     {
    //         h = height[i] <= height[j] ? height[i] : height[j];
    //         area = h * (j-i);
    //         if(area > max) max = area;
    //     }
    // }
    return max;