Leetcode11-Container With Most Water-Medium

时间:2022-03-03 20:03:28

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 and n is at least 2.

 

Leetcode11-Container With Most Water-Medium

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

 Example:

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


思路:

容器装水量 = 两点横坐标差值 * 两点纵坐标的最小值

要不重不漏的找出可以组成容器的所有组合:定义两个指针,i,j分别指向数组的前后端,计算容器装水量,取result较大值。并移动一步指针(either i or j, 两个指针不能同时移动),计算面积取较大值,直到i , j相遇。

注意:移动i还是j,看他们的height谁小就移动谁

j初始值是数组长度减1 ,不然再循环中访问不到数组元素,会抛出outofboundary异常。

代码:

class Solution {
    public int maxArea(int[] height) {
        int res = 0, i = 0, j = height.length - 1;
        while(i < j) {
            res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
            if (height[i] < height[j]) i++;
            else j--;
        }
        return res;
    }
}