数组类11--盛最多水的容器(M)

2019-08-06  本文已影响0人  干LeetCode
image.png

AC代码

public class Solution {
    public int maxArea(int[] height) {
        if(height == null || height.length == 0) {
            return Integer.MIN_VALUE;
        }   
        int left = 0;
        int right = height.length - 1;
        int maxArea = Integer.MIN_VALUE;
        while(left < right) {
            int tmp = (right - left) * (height[left] < height[right] ? height[left] : height[right]);
            if(tmp > maxArea) {
                maxArea = tmp;
            }
            if(height[left] < height[right]) {
                left++;
            }else {
                right--;
            }
        }
        return maxArea;
    }
}

精髓:

  1. 双指针
  2. 短板效应,比如看左指针,如果左指针的值比右指针的值小,说明当前左指针是短板,必须向右移动,如果不移动总面积不可能变大,因为就算右指针移动了,高度还是取左指针的值。
上一篇 下一篇

猜你喜欢

热点阅读