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

 [暴力解法]:

时间分析:

空间分析:

[思维问题]:

距离更近时,只有木板更高才能往前走,因此避免扫描多余状态。头一次总结到 对撞型两根指针的思考方向是这样,下次注意。

[一句话思路]:

用max反复比较,直到求出最大值

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(n)

同向行驶是n^2,相对行驶变成n

[英文数据结构或算法,为什么不用别的数据结构或算法]:

灌水问题就用 对撞型两根指针

[关键模板化代码]:

 while (left < right) 

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

public class Solution {
    /**
     * @param heights: a vector of integers
     * @return: an integer
     */
    public int maxArea(int[] height) {
        //corner case
        int max = 0;
        int left = 0;
        int right = height.length - 1;
        
        while (left < right) {
            max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
            if (height[right] > height[left]) {
                left++;
            }else {
                right--;
            }
        }
        return max;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8502849.html