Leetcode题解:11. Container With Most Water
2016-11-03 06:15
288 查看
Leetcode题解:11. Container With Most Water
难度:Medium题目:
Given 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 is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.Note: You may not slant the container.
中文简述
给你一串数组a1,a2….an,其中ai表示坐标系中的 (i,ai)即i位置上的垂直高度,其中每两条竖直的线都能组成一个容器来装水,问其中装水最多的容器的容积是多少思路
其实根据描述,我们知道容积V=(j-i)*min{ai,aj} (i < j)所以最简单的一个思路就是暴力找出所有容器的容积,然后比较他们的大小,这样做的时间复杂度为O(n^2)
转换一下思路,由于容器的容积取决于两边相隔距离和两边中较短边的高度。我们可以用贪心算法去化简:
①从最远的一对容器边找起,即i=0,j=n;
②从较短边开始向内搜索,计算容积比较大小。重复②直到i=j;
于是我们就能得到一个时间复杂度为O(n)的算法
class Solution { public: int maxArea(vector<int>& height) { int l=0, r=height.size()-1; int maxsize = 0; while(l<r){ if(height[l]<height[r]){ maxsize = (maxsize<(r-l)*height[l]? (r-l)*height[l]: maxsize); l++; } else{ maxsize = (maxsize<(r-l)*height[r]? (r-l)*height[r]: maxsize); r--; } } return maxsize; } };
相关文章推荐
- LeetCode(11)题解: Container With Most Water
- 11. Container With Most Water LeetCode题解
- LeetCode题解-11-Container With Most Water
- [LeetCode]11 Container With Most Water
- leetcode题解||Container With Most Water问题
- LeetCode 11 - Container With Most Water
- [leetcode 11]Container With Most Water
- leetcode 11 -- Container With Most Water
- [leetcode 11] Container With Most Water
- Java [leetcode 11] Container With Most Water
- LeetCode 11 Container With Most Water
- LeetCode 11 Container With Most Water (C,C++,Java,Python)
- LeetCode_11---Container With Most Water
- LeetCode42/11 Trapping Rain Water/Container With Most Water/Hist area**
- LeetCode 11 - Container With Most Water
- leetcode[11]Container With Most Water
- leetcode 11 Container With Most Water
- LeetCode-11 Container With Most Water(容器装水最大量)
- [Leetcode 43] 11 Container With Most Water
- leetcode_11题——Container With Most Water(两个指针)