1.贪心算法,从两头开始对比,哪头小就往里缩(这样就保证x从大到小开始比较,而且这样的情况下结果才有可能大于前者)
2.判别退出条件不是在vector中间,也有可能在两端,所以是i < j
自己写的代码:(19ms)
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
int maxArea(vector<int>& height);
int main()
{
vector<int> xx = { 2,3,4,5,18,17,6};
int are;
are = maxArea(xx);
cout << are;
getchar();
return 0;
}
int maxArea(vector<int>& height) {
int area = 0;
for (int i = 0, j = height.size() - 1; i < j ; )
{
if (height[i] > height[j])
{
if (area < (height[j] * (j - i)))
{
area = height[j] * (j - i);
}
j--;
}
else
{
if (area < (height[i] * (j - i)))
{
area = height[i] * (j - i);
}
i++;
}
}
return area;
}