一、问题描述
Description: Given
n non-negative integersa1,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.
给定 n 个非负整数
假定容器不可以倾斜。
二、解题报告
1. 解法一:O(n2)
直接遍历,枚举容器的两个边界,记录最大值:
class Solution { public: int maxArea(vector<int>& height) { int maxA = 0; for(int i=1; i<height.size(); ++i) { for(int j=i+1; j<height.size(); ++j) { if(height[i] < height[j]) maxA = height[i]*(j-i); else maxA = height[j]*(j-i); } } return maxA; } };
时间复杂度是
2. 解法二:O(n∗log2n)
这种方法,我们用一个vector<pair<int, int>>
来存储<高度, 下标>
,然后将 vector 按高度大小排序。排序之后,对于vector[i]
来说,vector[i+1,i+2,...,n-1]
的高度都比它大。
故以vector[i]
为较短边的容器中,要使水量最大,只需要距离最远,即分别计算vector[i+1,i+2,...]
内按原始位置排列最左边和最右边的直线,取两者的较大值。
bool cmp(pair<int,int> &p1, pair<int,int>&p2) { return p1.first < p2.first; } class Solution { public: int maxArea(vector<int>& height) { vector<pair<int, int>> v; // 表示<高度,下标> int n = height.size(); for(int i=0; i<n; ++i) v.push_back(make_pair(height[i], i+1)); sort(v.begin(),v.end(),cmp); // 排序 int left = v[n-1].second; // 记录最左边和最右边的位置 int right = left; int res = 0; for(int i=n-2; i>=0; --i) { res = max(res, max(v[i].first*(v[i].second-left), v[i].first*(right-v[i].second))); left = min(left, v[i].second); // 更新 right = max(right, v[i].second); } return res; } };
由于STL sort()是基于快排,时间复杂度是
AC 时间 68ms!
3. 解法三:O(n)
思路:两个指针 i, j 分别从前后向中间移动,两个指针分别表示容器的左右边界。每次迭代,先更新最大容量,然后把高度小的边界对应的指针往中间移动一位。
正确性:由于水的容量是由较小的那个边界决定的。在某次迭代中,假设 height[i] < height[j],那么 j 左移一位肯定不会使水的容量增大:
- 若 j 左移一位后,height[j] 仍然大于 height[i],由于距离缩短了,水的容量反而减少了。
- 若 j 左移一位后,height[j] 小于 height[i],由于距离缩短了,同时高度也减少了,水的容量也减少了。
所以,只有 i 增加才有可能使水的容量增大。
class Solution { public: int maxArea(vector<int>& height) { int res = 0; int i = 0; int j = height.size()-1; while(i < j) { res = max(res, (j-i)*min(height[i],height[j])); if(height[i] < height[j]) ++i; else --j; } return res; } };
AC 时间 20ms!
LeetCode答案源代码:https://github.com/SongLee24/LeetCode
来源:https://www.cnblogs.com/songlee/p/5738056.html