题目链接:点击打开链接
类型:two points
解法:遍历(超时)
public class Solution {
public int maxArea(int[] height) {
int len = height.length;
int max = 0;
if (len < 2)
return 0;
int side = 0;
int curr = 0;
for (int i = 0; i < len - 1; ++i)
{
for (int j = i + 1; j < len; ++j)
{
side = (height[i] > height[j]) ? height[j] : height[i];
curr = (j - i) * side;
max = (max > curr) ? max : curr;
}
}
return max;
}
}
解法:两端向中间搜索
public class Solution {
public int maxArea(int[] height) {
int len = height.length;
int max = 0;
if (len < 2)
return 0;
int left = 0;
int right = len-1;
int curr = 0;
while (left < right)
{
curr = (right-left)*Math.min(height[left], height[right]);
max = Math.max(max, curr);
if (height[left] > height[right])
{
--right;
}
else
{
++left;
}
}
return max;
}
}