Leetcode 11. Container With Most Water (two pointers)

Posted wz30

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 11. Container With Most Water (two pointers)相关的知识,希望对你有一定的参考价值。

Leetcode: 11

there are two ways to deal with two pointers

one is O(n), two pointers moves from both side

Another is O(2N), two pointer move from the same side

 

Idea for this, choose the first one and then if there is a smaller one, change that corresponding pointer until bigger that the prior bigger one.

class Solution {
    public int maxArea(int[] height) {
        //two pointers -> N 
        //two pointers -> 2*N
        //6,5,4,7,8,2,4,6,9,
        //1 2 3 4 5 6 7 8 9
        //idea: (i ++) (j--) , for two points pointed by two pointers, there must be one big and one small, change the pointer pointed to small so that mamimize the possibility
        int i = 0;
        int j = height.length-1;
        int max  = 0;
        while(i<j){//if i==j break
            //compute the area
            if(height[i]>height[j]){//i bigger
                int temp = (j-i)*(height[j]);
                if(temp>max) max = temp;
                j--;
            }else {
                int temp = (j-i)*(height[i]);
                if(temp>max) max = temp;
                i++;
            }
        }
        return max;
    }
}

 

haishi cai

以上是关于Leetcode 11. Container With Most Water (two pointers)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode?????????python?????????11. Container With Most Water

LeetCode11. Container With Most Water 解题报告

leetcode_11. Container With Most Water

Leetcode 11. Container With Most Water (two pointers)

LeetCode 11. Container With Most Water

leetcode11 Container With Most Water