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

Leetcode11 Container With Most Water

时间:2018-11-21 22:15:08      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:mos   code   min   water   for   containe   inter   contain   color   

首先想到的肯定是暴力解法,O(n^2)。

class Solution {
    public int maxArea(int[] height) {
//        int[][] dp = new int[height.length][height.length];
        int max=0;
        for(int i=0;i<height.length-1;i++) {
            for(int j=i+1;j<height.length;j++) {
//                dp[i][j]=(j-i)*Math.min(height[i], height[j]);
                max = Math.max(max, (j-i)*Math.min(height[i], height[j]));
            }
        }
        return max;
    }
}

421ms,8.51%,肯定不行,思考更优解法。

自己想到了two pointer,但是没有彻底想明白,看了solution后明白了。

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

6ms,66.7%,O(n)。和3ms答案基本一个思路了,可以了。

Leetcode11 Container With Most Water

标签:mos   code   min   water   for   containe   inter   contain   color   

原文地址:https://www.cnblogs.com/chason95/p/9984592.html

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