题目
题目要求
暴力(超时)
class Solution {
public int maxArea(int[] height) {
int max = 0;
int start = 0;
int end = height.length;
for(int i = 0; i < height.length; i ++) {
for (int j = height.length -1; j > i; j--) {
int dis = j - i;
int temp = 0;
temp = (height[i]> height[j] ? height[j]:height[i]) * dis;
if (temp > max) {
max = temp;
}
}
}
return max;
}
}
使用双指针(O(n))复杂度
class Solution {
public int maxArea(int[] height) {
int size =height.length;
int left = 0, right = size - 1;
int result = 0;
while (left < right) {
int temp = (right - left) * (height[right] > height[left] ? height[left] : height[right]);
if (temp > result) {
result = temp;
}
if(height[left] > height[right]){
right--;
} else {
left++;
}
}
return result;
}
}
### 使用双指针跳过方式,进一步提高效率
```java
class Solution {
public int maxArea(int[] height) {
int max = 0;
int l =0, r = height.length - 1;
while (l < r) {
int min = Math.min(height[l], height[r]);
int temp = min * (r - l);
max = Math.max(max, temp);
while (height[l] <= min && l < r) {
++l;
}
while (height[r] <= min && l < r) {
--r;
}
}
return max;
}
}