题目描述

LeetCode盛最多水的容器_双指针

看到这题,显然像我这种菜鸡首先想到的当然是暴力法

int maxArea(vector<int>& height) {
int len = height.size();
int area = INT_MIN;
for(int i=0; i<len-1; i++){
for(int j=i+1; j<len; j++){
int temp = (height[i]<height[j]? height[i] : height[j]) * (j-i);
area = temp > area? temp : area;
}
}
return area;
}

虽然结果正确,显然效率低下,我还以为肯定会超时,没想到居然过了

LeetCode盛最多水的容器_暴力法_02


惨不忍睹,并不想多说什么。于是开始向网友寻求更高效的解法,有了下面的第二版(双指针)

int maxArea(vector<int>& height) {
int area = INT_MIN;
int low = 0;
int high = height.size()-1;
while(low < high){
int h = height[low]<height[high] ? height[low] : height[high];
area = area > h*(high-low) ? area : h*(high-low);
if(height[low]<height[high]) low++;
else high--;
}
return area;
}

LeetCode盛最多水的容器_i++_03


确实快多了,看来算法的学习之路还很漫长…