题目
11. 盛最多水的容器
思路
我一开始写的暴力,时间复杂度O(n2)的那种,超时。
原来可以O(n)解决的。
直接看答案的思路:https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
代码
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;
}
};
网友评论