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.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Thinking:

  • Method1: 通过双指针从左右分别向中间靠拢。
class Solution {
    public int maxArea(int[] height) {
        int i = 0;
        int j = height.length - 1;
        int result = 0;
        int temp = 0;
        while(j > i){
            int h1 = height[i];
            int h2 = height[j];
            temp = (j - i) * Math.min(h1, h2);
            if(temp > result) result = temp;
            if(h1 >= h2){
                j--;
                continue;
            }else{
                i++;
                continue;
            }
        }
        return result;
    }
}

二刷

  1. 和一刷时使用的方法是一致的。
  2. 分析:
    • 首先在双指针靠拢的过程中,长方形的一条边是一直减小的,所以我们在靠拢的过程中,想要发现长边中的短边更长。
class Solution {
    public int maxArea(int[] height) {
        if(height == null || height.length == 0) return 0;
        int low = 0, high = height.length - 1;
        int max = 0;
        int temp = 0;
        while(low < high){
            if(height[low] < height[high]){
                temp = height[low] * (high - low);
                low ++;
            }else{
                temp = height[high] * (high - low);
                high --;
            }
            max = Math.max(max, temp);
        }
        return max;
    }
}