两个指针。水的多少取决于最短的那块板,
所以移动较短的那块板的指针向前或往后。
/**
* @author johnsondu
* @problem Container With Most Water
* @time O(n)
* @space O(1)
* @url https://leetcode.com/problems/container-with-most-water/
* @strategy two pointers, move the minimum one's index forward or backward.
* @status Accepted, runtime beats 11.42% of cpp submissions. 28ms
* @time 19:54, Nov 3th 2015
*/
class Solution {
public:
int maxArea(vector<int>& height) {
const int len = height.size();
int lf = 0;
int rt = len - 1;
int ans = -1;
while(lf < rt) {
int cnt = min(height[rt], height[lf]) * (rt - lf);
ans = max(cnt, ans);
if(height[lf] < height[rt]) lf ++;
else rt --;
}
return ans;
}
};
本文介绍了一种使用双指针法解决水桶问题的优化算法,通过移动较短水桶的指针来寻找盛水量最大的水桶组合,实现O(n)的时间复杂度和O(1)的空间复杂度。
258

被折叠的 条评论
为什么被折叠?



