本题来自 LeetCode:11. Container With Most Water[1]
题目描述
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
暴力法
题目分析
本题可以通过暴力法来解答,采用双层循环,迭代出最大值。
题目解答
class Solution {
public int maxArea(int[] height) {
int max = Integer.MIN_VALUE;
for(int i = 0; i height.length - 1; i ++) {
for(int j = i + 1; j height.length; j ++ ) {
max = Math.max(max, Math.min(height[i], height[j]) * (j - i));
}
}
return max;
}
}
复杂度分析:
时间复杂度:
O(n ^ 2)
空间复杂度:
O(1)
双指针
题目分析
注意到,要使面积最大,在相同的条件下,要么是左右两条边之间的距离越长,要么是左右两条边的最小长度越大。
而如果是左右两条边之间的距离变短的情况下,那么就需要左右两条边的最小长度越大,面积才有可能变大。
题目解答
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int max = Integer.MIN_VALUE;
while(left right) {
// 比较最大值
max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
if(height[left] height[right]) {
// 若左边长度小于右边长度,则收缩左边
left ++;
} else {
// 否则收缩右边
right --;
}
}
return max;
}
}
复杂度分析:
时间复杂度:
O(n)
空间复杂度:
O(1)
参考资料
- Container With Most Water: https://leetcode-cn.com/problems/container-with-most-water
原文始发于微信公众号(xiaogan的技术博客):