码迷,mamicode.com
首页 > 其他好文 > 详细

11. Container With Most Water 装水最多的容器

时间:2018-03-03 21:22:37      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:width   模板   数据   gpo   form   solution   特殊情况   ace   避免   

[抄题]:

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)

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

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

[关键模板化代码]:

 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

 

11. Container With Most Water 装水最多的容器

标签:width   模板   数据   gpo   form   solution   特殊情况   ace   避免   

原文地址:https://www.cnblogs.com/immiao0319/p/8502849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!