Leetcode:Container With Most Water

来源:互联网 发布:淘宝店运费险怎么算的 编辑:程序博客网 时间:2024/06/01 07:16

Container With Most Water

 

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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轴的坐标,数组元素值则为高度。求能围成的容器的最大面积。

我们用两个变量left和right来分别指向数组的最左边和最右边,然后进行循环,循环条件为while(left<right)。此时left和right围成的面积为(right-left)*(a[left],a[right]中的较小者)。循环继续的条件:if(a[left]<a[right]),则left++;if(a[left]>a[right]),则right++。循环中记录下最大的面积max,循环结束时max的值,则为所能围城的最大面积。

实现代码如下:

public class Solution {    // for any i, the maxium area will be the farthest j that has a[j] > a[i];    public int maxArea(int[] height) {        if(height == null || height.length < 2) {            return 0;        }        int max = 0;        int left = 0;        int right = height.length -1;        while(left < right) {            max = Math.max( max, (right - left) * Math.min(height[left], height[right]));            if(height[left] < height[right]){                left++;            } else {                right--;            }        }        return max;            }}C++ Version-------------------class Solution {public:    int maxArea(vector<int> &height) {        int max = 0, area;        int start = 0, end = height.size() - 1;        while (start < end) {            if (height[start] > height[end]) {                area = height[end] * (end - start);                end --;            } else {                area = height[start] * (end - start);                start ++;            }            if (area > max) {                max = area;            }        }        return max;    }};


0 0
原创粉丝点击