【leetcode】Array——Container With Most Water(11)

題目: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.

思路:本以爲和之前的題目:Largest Rectangle in Histogram解題思路一樣,細想也不是。參考了leetcode的解法:https://leetcode.com/discuss/59635/easy-concise-java-o-n-solution-with-proof-and-explanation也許這個解法不好理解,還可以看看這個:https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm

總結一下思路:

兩個指針:left=0 right=height.length-1 。假如left=0,right=6:

如果height[left]<height[right],則0-5 0-4 … 0-1 都要比0-6小(準確來說是不可能比0-6大),所以left++。

如果height[left]>height[right],則1-6 2-6 … 5-6 都要比0-6小(準確來說是不可能比0-6大),所以right--

代碼:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章