美文网首页
LeetCode11. Container With Most

LeetCode11. Container With Most

作者: 派大星的博客 | 来源:发表于2018-11-12 17:38 被阅读3次
image.png

我的C解法

#include <stdio.h>

int maxValue(int x, int y) {
    if (x <= y) {
        return y;
    } else {
        return x;
    }
}

int minValue(int x, int y) {
    if (x <= y) {
        return x;
    } else {
        return y;
    }
}

int maxArea(int* height, int heightSize) {
    int area = 0;
    int left = 0;
    int right = 0;
    int i = 0;
    int j = heightSize - 1;
    while (i < j) {
        int min = minValue(left, right);
        int tmp = min * (j - i);
        area = maxValue(tmp, area);
        printf("area_tmp = %d i = %d j = %d\n", area,i,j);
        if (left <= right) {
            while (height[i] <= left) {
                i ++;
                if (i >= j) { break;}
            }
            left = height[i];
        } else {
            while (height[j] <= right) {
                j --;
                if (i >= j) { break;}
            }
            right = height[j];
        }

    }
    return area;
}

int main(int argc, const char * argv[]) {
    int a[] = {1,8,20,2,5,4,8,29,10,8};
    int len = sizeof(a)/sizeof(int);
    int x = maxArea(a, len);
    printf("len  = %d\n",len);
    printf("area = %d\n",x);
    return 0;
}

别人的C解法

int maxArea(int* height, int heightSize) {
    int left = 0;
    int right = heightSize - 1;
    int area = 0;
    
    while(left < right) {
        int a = (right - left) * ((height[left] > height[right])? height[right] : height[left]);
        if(a > area)
            area = a;
        if(height[left] > height[right])
            right--;
        else
            left++;
    }
    
    return area;
}

相关文章

网友评论

      本文标题:LeetCode11. Container With Most

      本文链接:https://www.haomeiwen.com/subject/kkicfqtx.html