您的位置:首页 > 大数据 > 人工智能

【LeetCode】Container With Most Water

2014-03-11 14:30 281 查看
Container With Most Water

Total Accepted: 6700 Total Submissions: 22080 My Submissions

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 line i 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.

题目大意是求解两条木板和横轴组成的空间,可以装最多的水,图形化表示就是这样子:



解题思路类似Two Sum,有两个指针,从头和尾向中间靠近,假设这两个指针为low和high。

当指针在头和尾的时候,其实这个时候长度最长,但是高度取决于Math.min(A[low],A[high])。

往中间走的话,长度会减小,但是高度有可能增高。

如果还有面积最大值的话,并且高度只能向Math.max(A[low],A[high])靠近,那么只能在low+1到high或者low到high-1之间。

当然也可以暴力搜索,时间复杂度为O(N*N),大数据的话必然超时。

Java AC

public class Solution {
    public int maxArea(int[] height) {
        int len = height.length;
        int max = 0;
        int low = 0;
        int high = len-1;
        while(low < high){
            int area = (high - low) * Math.min(height[low], height[high]);
            max = Math.max(area, max);
            if(height[low] <= height[high]){
                low++;
            }else{
                high--;
            }
        }
        return max;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: