1. 程式人生 > >【LeetCode】11. Container With Most Water 解題報告

【LeetCode】11. Container With Most Water 解題報告

Subject

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.

Explain

給定n個非負的整數a1,a2 ……an, 去哦中每個代表一個點座標(i, ai)。一共n個垂直線段。找到兩個線段,與X軸形成一個容器,使其能剩最多的水。

其實就是找到這兩條線段之後,用最短的線段的長度 * 兩個線段之間的距離。

Solution

solution 1

通過巢狀迴圈來做。很明顯,這是比較笨的方法,也是最容易想到的方法。

時間複雜度也就是o(n²)了。

    /**
     * 時間複雜度o(n²)
     * 
     * @param height
     * @return
     */
public int maxArea1(int[] height) { if (height == null || height.length < 2) { return 0; } int result = 0; int temp = 0; for (int i = 0; i < height.length; i++) { for (int j = i + 1; j < height.length; j++) { temp = (j - i) * Math.min(height[i], height[j]); if
(temp > result) { result = temp; } } } return result; }

solution 2

通過兩個“指標”,分別指向頭和尾。

分別往中間移動,
當 “左指標” 指向的線段長度小於“右指標”指向的線段長度,則移動 “左指標” 。
反之,移動“右指標”。

    /**
     * 
     * @param height
     * @return
     */
    public int maxArea2(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int left = 0;
        int right = height.length - 1;
        int result = 0;
        int temp = 0;

        while (left < right) {
            temp = (right - left) * Math.min(height[left], height[right]);
            result = Math.max(result, temp);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }

        return result;
    }

時間複雜度是o(n)。

bingo~~