[LeetCode] 11. 盛最多水的容器

之前做过的想不起来了,只想到用两个指针,具体怎么走忘记。

https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/

每次选定围成水槽两板高度 h[i],h[j]中的短板,向中间收窄 1 格。

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

 

 更快一点的方法是:

class Solution {
    public int maxArea(int[] height) {
        int i = 0;
        int j = height.length-1;
        int maxarea = 0;
        while(i<=j){
            if(height[i]<height[j]){
                int temp = height[i] * (j-i);
                if(temp > maxarea)
                    maxarea = temp;
                i++;
            }else{
                int temp = height[j] * (j-i);
                if(temp > maxarea)
                    maxarea = temp;
                j--;
            }
        }
        return maxarea;
    }
}

方法都一样,就是换了一种写法就快了这么多。。。

 

posted @ 2020-04-19 23:23  doyi  阅读(116)  评论(0编辑  收藏  举报