11. 盛最多水的容器

2020-03-14  本文已影响0人  lazy_ccccat

题目

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/

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;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读