Wednesday, October 7, 2015

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.
Solution1:  这写的是神马!!!请看solution2

public class Solution {
    public int maxArea(int[] height) {
        int len = height.length;
        int i = 0, j =len - 1;
        int left = height[0], right = height[len - 1];
        int area = 0, temp = 0;
        
        while(i < j) {
            temp = Math.min(left, right) * (j - i);
            area = Math.max(temp, area);
           
            if(left < right) {
                while(i < j && height[i] <= left) {
                    i++;
                }
                if(i < j && height[i] > left)
                    left = height[i];
            }else {
                while(i < j && height[j] <= right) {
                    j--;
                }
                if(i < j && height[j] > right)
                    right = height[j];
            }
        }
        return area;
    }
}
Solution2: run time complexity is O(n), constant space. 
两个指针,从两边往中间扫。夹逼法。
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 max = 0;
        while (left < right) {
            int h = Math.min(height[left], height[right]);
            int area = (right - left) * h;
            max = Math.max(max, area);
            
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        
        return max;
    }
}

No comments:

Post a Comment