美文网首页
11. 盛最多水的容器

11. 盛最多水的容器

作者: lazy_ccccat | 来源:发表于2020-03-14 21:34 被阅读0次

题目

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;
    }
};

相关文章

网友评论

      本文标题:11. 盛最多水的容器

      本文链接:https://www.haomeiwen.com/subject/zuloshtx.html