【LeetCode】LeetCode——第11題:Container With Most Water
阿新 • • 發佈:2019-02-04
11. Container With Most Water
My Submissions Total Accepted: 75667 Total Submissions: 219100 Difficulty: MediumGiven 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
Note: You may not slant the container.
Subscribe to see which companies asked this question
Show Tags Show Similar Problems題目的大概意思是:給定一些擋板,取兩個擋板使得蓄水量最大,並輸出最大蓄水量。當然,蓄水的高度由兩個擋板中較小者決定。
這道題難度等級:中等
看到這個題的第一反應就是用雙指標法,即l、r往中間靠攏,這裡的中間是泛指。
程式碼如下:
class Solution { public: int maxArea(vector<int>& height) { int l = 0, r = height.size() - 1; int max_Area = 0; while (l < r){ max_Area = max(max_Area, (r - l) * min(height[l], height[r])); height[l] > height[r] ? (r--) : (l++); } return max_Area; } };
提交程式碼後順利AC掉,Runtime: 24 ms。