leetcode第11題——**Container With Most Water

題目

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.

Note: You may not slant(傾斜) the container.

思路

大意是數組下標i和非負數組值a[i]組成一個座標點(ia[i]),要找出兩條縱線和x軸組成一個容器,使得容器能容納最多水(不能“傾斜”該容器)。假設有(ia[i])和(ja[j])兩個座標(j > i),容積取決於min(a[i],a[j]) * (j - i)。
採用兩層循環嵌套肯定是不能通過的,因爲時間複雜度爲o(n^2),輸入大數組時嚴重超時。採用從兩端向中間靠攏的辦法,即 j - i 的值逐漸減小,這時高肯定要增大才可能取得更大的面積,按照這種思路不斷更新i和j的值(i增大或者j減小),直到不滿足i < j 時就能得到最優解。

代碼

Python

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        i = 0
        j = len(height) - 1
        res = 0
        while(i < j):
            res = max(res,min(height[i],height[j])*(j-i))
            if(height[i] < height[j]):
                k = i
                while (k < j) and (height[k] <= height[i]):
                    k += 1
                i = k
            else:
                k = j
                while (k > i) and (height[k] <= height[j]):
                    k -= 1
                j = k
        return res

Java

public class Solution {
    public int maxArea(int[] height) {
        int res = 0;
		int i = 0;
		int j = height.length - 1;
		int k;
		if (j < 1) return 0;
		//從兩端向中間靠攏,找出比兩端的線高的位置
		while (i < j){
			res = Math.max(res,Math.min(height[i], height[j])*(j - i));
			//左低右高,則找出最靠近i且比height[i]高的位置
			if (height[i] < height[j]){
				for(k = i;k < j && height[k] <= height[i];k++);
				i = k;
			}
			//右低左高,則找出最靠近j且比height[j]高的位置
			else{
				for(k = j;k > i && height[k] <= height[j];k--);
				j = k;
			}
		}
		return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章