011 - Container With Most Water

来源:互联网 发布:数据挖掘导论 豆瓣 编辑:程序博客网 时间:2024/05/01 14:23

Given n non-negative integers a1, a2, ...,an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of linei is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.


这个题目的意思是这样的:

在x轴坐标系的正整数点1, 2, 3, 4...

每个点对应的y轴高度为a1, a2, a3, a4...

现在在x轴上找两个点,使得这两个点之间能装的水最多


我的想法如下:

#define MIN(x,y) ((x) > (y)? (y) : (x))int maxArea(int* height, int heightSize){    int area = 0;    int maxi, max = 0;    int i, j, k;    for (i = 0; i < heightSize; i++)    if (height[i] > max) {    max = height[i];maxi = i;    }    for (i = 0; i <= maxi; i++) {    for (j = heightSize - 1; j >= maxi; j--) {k = MIN(height[i], height[j]) * (j - i);if (k > area) area = k;}    }    return area;}

参考别人的想法,我没有去证明为什么这样可以找到

#define MIN(x,y) ((x) > (y)? (y) : (x))int maxArea(int* height, int heightSize){    int area = 0, k;    int i = 0, j = heightSize - 1;    while (i < j) {    k = MIN(height[i], height[j]) * (j - i);if (k > area) area = k;if (height[i] <= height[j]) i++;else j--;    }    return area;}


0 0
原创粉丝点击