# LeetCode 11. Container With Most Water题目分析代码

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. Note: You may not slant the container and n is at least 2. Subscribe to see which companies asked this question.

Paste_Image.png

# 代码

```public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
int computeArea(int left, int right,  int[] heights) {
return (right-left)*Math.min(heights[left], heights[right]);
}

public int maxArea(int[] heights) {
//两根指针，一头一尾计算，短的那根指针向中间移动，因为只有这种情况才存在更大的情况
int left = 0, right = heights.length-1;
int res = 0;

while(left < right) {
res = Math.max(res, computeArea(left,right,heights));
if(heights[left] < heights[right]) {
left++;
//如果小于则不必要计算，直接跳过
while(heights[left] <= heights[left-1] && left<right)
left++;
}
else {
right--;
while(heights[right] <= heights[right+1] && left <right)
right--;
}
}
return res;
}
}```

381 篇文章35 人订阅

0 条评论

## 相关文章

813

### BZOJ4766: 文艺计算姬

Description "奋战三星期，造台计算机"。小W响应号召，花了三星期造了台文艺计算姬。文艺计算姬比普通计算机有更多的艺 术细胞。普通计算机能计算一个带...

3378

2955

2842

### tensorflow学习笔记（二十七）：leaky relu

tensorflow leaky relu 在tensorflow 0.12.0及之前，都没有内置的leaky relu函数，那么我们如何实现leaky rel...

2848

3586

38310

4146

### 时间复杂度的概念以及计算

The time complexity of an algorithm quantifies the amout of time taken by an alg...

1142

1072