11. Container With Most Water

Container With Most Water
谁小移动谁, 从两遍像中间走 https:
//www.youtube.com/watch?v=IONgE6QZgGI Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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.    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.   Example: Input: [1,8,6,2,5,4,8,3,7] Output: 49 class Solution { public int maxArea(int[] height) { int ans = 0; int left = 0; int right = height.length - 1; while(left < right){ ans = Math.max(ans, Math.min(height[left], height[right]) * (right - left)); if(height[left] < height[right]){ left++; }else{ right--; } } return ans; } } // time : n // height[left] < height[right], if move right towards the inner part. its guarentred that // the area is gonna be smaller, draw a graph and see if makes sense // if move left pointer towards the inner, the area can be larger, samller or equal, we don't // really know, it depends on the the second left value, the one we are currently at. // between a choice that the area is def gonna be smaller and a choice that the area might be larger // or smaller or the same, we choose the later // // move two pointers from opposite directions towards the inner is searching for a better area , bigger one

 

42. Trapping Rain Water


Sol1: 
Time 

Space 


class Solution {
    public int trap(int[] height) {
        if(height == null || height.length == 0) return 0;
        int res = 0;
        int n = height.length;
        int[] leftMax = new int[n];
        int[] rightMax = new int[n];
        
        leftMax[0] = height[0];
        rightMax[n - 1] = height[n-1];
        
        
        // from left to right
        for(int i = 1; i < n; i++){
            leftMax[i] = Math.max(height[i], leftMax[i-1]);
        }
        
        for(int j = n - 2; j >= 0; j--){
            rightMax[j] = Math.max(height[j], rightMax[j + 1]);
        }
        
        for(int i = 0; i < n; i++){
            res += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return res;
    }
}

================

Solution 2 : space O(1)

https://www.youtube.com/watch?v=8BHqSdwyODs

Idea: two pointers from opposite directions, whose max is smaller, get the result from that side 

 

 

 

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

posted on 2018-08-28 21:24  猪猪&#128055;  阅读(109)  评论(0)    收藏  举报

导航