题目
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.
翻译
给定n个非负整数a1,a2,…, an,每一个整数表示一点在(i,ai)的点。然后垂直于x轴向下划线。然后求线(i,ai)和(j,aj)还有x轴所能容纳最大的水量
分析
1,首先也是暴力法,即计算每两个线之间的容量。发现超时,因为此时的时间复杂度为O(n^2)
代码1
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int max = 0;
for(int i = 0; i < len; i ++){
for(int j = i+1;j < len; j++){
int tmp = std::min(height[i],height[j])*(j-i);
if(tmp > max){
max = tmp;
}
}
}
return max;
}
};
2,经过看比人博客发现自己方法太糙了。
比如A[] = [1,2,5,3,2,2,4]。使用双指针法。start ,end
因为比如start = 0 end = 6时,容积为1*6。如果end -1 。此时容积为1*5。即当前容积有其中最小值决定。
所以
如果A[start] < A[end]. start ++;
如果A[start] > A[end] end –;
然后计算当前start和end之间的最大值。更新max
代码
class Solution {
public:
int maxArea(vector<int>& height) {
int len = height.size();
int max = 0;
int start = 0;
int end = len -1;
while(start < len){
int tmp = 0;
if(height[start] > height[end]){
tmp = height[end]*(end-start);
end --;
}else{
tmp = height[start]*(end-start);
start++;
}
if(tmp > max){
max = tmp;
}
}
return max;
}
};