Container With Most Water--LeetCode

Container With Most Water

(原題鏈接:點擊打開鏈接)

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.

Note: You may not slant the container and n is at least 2.

Solution:

超時(時間複雜度爲O(N^2)):

class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxWater = 0;
        int localheight = 0;
        for (int a = 0; a < height.size() - 1; a++)
        {
            for (int b = a + 1; b < height.size(); b++)
            {
                localheight = height[a] > height[b] ? height[b] : height[a];
                int localWater = localheight * (b - a);
                maxWater = maxWater > localWater ? maxWater : localWater;
            }
        }
        return maxWater;
    }
};

我們從上面方法中可以得到a總是小於b的。而且中間會做很多無用功。所以我們可以嘗試一下將方法改良,變成a,b分別指示兩端,並且向中間移動,而不是雙層循環。此時時間複雜度變爲爲O(N):

當height[a] <= localheight && a < b時,此時假設是a變大引起的改變,b-a減少,height[a]也不能使localheight增大,即localheight不變或減少,此時localWater肯定是減少的,沒有意義,所以就不用再計算這個值,它是不會使maxWater發生變化的。

當height[b] <= localheight && a < b時,此時假設是b變小引起的改變,b-a減少,height[b]也不能使localheight變大,所以此時localWater肯定是減少的,沒有意義,同樣不用計算。

a,b向中間移動直至a == b

class Solution {
public:
    int maxArea(vector<int>& height) {
        int maxWater = 0;
        int localheight = 0;
        int a = 0;
        int b = height.size() - 1;
        while (a < b)
        {
            localheight = height[a] > height[b] ? height[b] : height[a];
            int localWater = localheight * (b - a);
            maxWater = maxWater > localWater ? maxWater : localWater;
            while (height[a] <= localheight && a < b) a++;
            while (height[b] <= localheight && a < b) b--;
        }
        return maxWater;
    }
};





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