[LeetCode] Container With Most Water 簡要分析

前言

這題非要說貪心的話也算是吧,不過最主要的特徵還是雙指針。LC的題好像不少都是扔倆頭尾指針然後遍歷一遍完事兒的。這道題倒是“短板效應”的不錯體現了。

題目

題目鏈接

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.

思路

自己做的PPT

圖片看不清楚的話可右鍵複製鏈接轉到圖牀再看。

代碼

class Solution {
public:
    int maxArea(vector<int>& height) {
        int first = 0;
        int end = height.size() - 1;
        int result = INT_MIN;
        while (first < end) 
        {
            int width = end - first;
            int board = height[end]<height[first]?height[end]:height[first];
            int area = board*width;
            result = result>area?result:area;
            if (height[first] <= height[end]) 
                first++;
            else
                end--;
        }
        return result;
        }
};

其他

JAVA果然過得比CPP快,Python和C#依舊墊底。

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