題目
11. 盛最多水的容器
思路
我一開始寫的暴力,時(shí)間復(fù)雜度O(n2)的那種,超時(shí)。
原來(lái)可以O(shè)(n)解決的。
直接看答案的思路:https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/

image.png
代碼
class Solution {
public:
int maxArea(vector<int>& height) {
int area = 0;
int left = 0, right = height.size() - 1;
while (left < right) {
area = max(min(height[left], height[right]) * (right - left), area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return area;
}
};