LeetCode解题 11:Container With Most Water
Problem 11: Container With Most Water [Medium]
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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
来源:LeetCode
解题思路
1. 暴力求解
使用二重循环,遍历
n
(
n
−
1
)
2
\frac{n(n-1)}{2}
2n(n−1)对组合的容量,返回最大值。
时间复杂度O(
n
2
n^2
n2)。
2. 双指针
使用双指针指向数组的头和尾,并在循环中不断将指向较短线段的指针向内移动,同时不断更新最大容量的数值,直到两个指针指向同一位置。
移动原理: 初始指针的位置在x轴上的长度是最长的,但将指向较短线段的指针向内移动时,虽然x轴上的长度变短,却有可能因为指向的线段变长而使总容量变长。
整个过程只对数组进行了一次遍历,因此时间复杂度为O(
n
n
n)。
Solution (Java)
双重循环:
class Solution {
public int maxArea(int[] height) {
int N = height.length;
int water, max = 0;
for(int i = 0; i < N; i++){
for(int j = i+1; j < N; j++){
water = Math.min(height[i], height[j]) * (j-i);
max = Math.max(max, water);
}
}
return max;
}
}
双指针:
class Solution {
public int maxArea(int[] height) {
int N = height.length;
int max = 0;
int left = 0, right = N-1;
while(left != right){
max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
if(height[left] < height[right]) left += 1;
else right -= 1;
}
return max;
}
}