2015年6月29日星期一

Container With Most Water leetcode

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.
brute force方法是对每一对都求面积, 然后比较面积 要遍历两次  时间复杂度O(n^2)
另外一种方法是two points的方法, 从两头开始计算面积, 因为蓄水面积是由短板决定的, 每次比较左右point 哪个是短板就移动哪一个, 这样只扫面一次数组 时间O(n)

public class Solution {
    public int maxArea(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int left = 0;
        int right = height.length - 1;
        int area = 0;
        while (left < right) {
            area = Math.max(area, Math.min(height[left], height[right]) * (right - left));
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return area;
    }
}

没有评论:

发表评论