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 and n is at least 2.

題目大意:給定一個長度爲n的數組a[n],在二維空間形成n個點(x=i,y=a[i]),找出兩個點,使得這兩個點到x軸的垂線與x軸構成一個容器,容器的容積最大。容器不能傾斜,而且n>=2。

解題思路:

對於n個點,要求得最大的容積,可以分兩種情況:

1. 寬度爲n,高度爲a[0]和a[n-1]中較小的值;

2. 捨棄掉(i,a[i])這個點,其中i = a[0]和a[n-1]中較小的值的下標,然後在剩下的n-1個點中找得兩個點,構成容積最大的容器。

直到寬度爲1的時候,直接去高度爲a[i]。


遞歸代碼:(leetcode測試用例太大,報了StackOverFlow)

class Solution {
    public int findMax(int left, int right, int[] height) {
		if (right - left == 1) {
			return Math.min(height[left], height[right]);
		}
		int bigger;
		if (height[left] > height[right]) {
			bigger = findMax(left, right - 1, height);
		} else {
			bigger = findMax(left + 1, right, height);
		}
		return Math.max(Math.min(height[left], height[right]) * (right - left), bigger);
	}

	public int maxArea(int[] height) {
		return findMax(0, height.length - 1, height);
	}
}



循環代碼:(10ms,beats 52.47%)

class Solution {
    public int maxArea(int[] height) {
		int len = height.length;
		int[] area = new int[len];
		int left = 0, right = len - 1;
		while (right > left) {
			area[right - left - 1] = (right - left) * Math.min(height[left], height[right]);
			if (height[left] > height[right]) {
				right--;
			} else {
				left++;
			}
		}
		int max = 0;
		for (int i = 0; i < len; i++) {
			if (area[i] > max) {
				max = area[i];
			}
		}
		return max;
	}
}



發佈了251 篇原創文章 · 獲贊 274 · 訪問量 73萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章