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.

分析:若干條線,找兩條線使得其與X軸圍成的面積最大。
如果是暴力的窮搜,肯定可以得到答案,但複雜度達到O(N^2),耗時,leetcode裏面是過不去的。

思路:從數據集的兩頭同時開始。當ai小於aj時,i ++; 反之,j–。直到二者相遇。理由,影響面積的是比較短的線,因此,每次只要改變比較短的線就好了。這個想法的複雜度是O(N)

代碼:

int maxArea(vector<int>& height) {
        int len = height.size();
        int max_area = 0, area = 0;

        int i = 0, j = len - 1;
        while(i < j)
        {
            if(height[i] < height[j])
            {
                area = (j -i) * height[i];
                i ++;
            }
            else
            {
                area = (j - i) * height[j];
                j --;
            }
            if (area > max_area)
            {
                max_area = area;
            }
        }
        return max_area;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章