1. 程式人生 > >[LeetCode]11. Container With Most Water 盛最多水的容器

[LeetCode]11. Container With Most Water 盛最多水的容器

Given n non-negative integers a1, a2, ..., a, 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

題目給出[a1,a2...ai],要求找出一個ai,aj是的min(ai,aj)*(j-i)最大。
有兩種方法:
(1)暴力法
兩層迴圈從左到右遍歷,算出每一組的面積大小
public class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0;
        for (int i = 0; i < height.length; i++)
            for (int j = i + 1; j < height.length; j++)
                maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i));
        return
maxarea; } }

兩層迴圈,複雜度自然是O(n^2)

(2)雙指標法

現在假設[a1,a2......an],現在我們算出s=min(a1,an)*(n-1),1和n是長度的邊界,剩下的任意高度組合的長度都不能比n-1大,長度如果變成了n-2,

之前算出的面積s如果不想變小,min(ai,aj)就必須比min(a1,an)大。總結一下就是,隨著長度的縮小,面積要想變大就必須擴大高度,所以比原先高度低的我們就

不需要再考慮了。

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

一次遍歷就能解決,時間複雜度O(n)