Container With Most Water Leetcode
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.
这道题乍一看很吓人,但其实如果一开始想不到最优的解法,可以试着从暴力解法入手,就能想到更好的方法了。另外two pointers应用挺多的,可以首先想一下。
实现很简单。。。稍稍优化下就和top solution一样啦
public class Solution { public int maxArea(int[] height) { int max = 0; int left = 0; int right = height.length - 1; 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; } }
做第二遍的时候,其实严重怀疑自己当时并没有完全理解这道题目。。。
为什么左边比右边小就可以移动左边的pointer了?原因是大概是一个因子变小了,另一个要变大才有可能使得总量超过原来的值。懒得看证明了。。。要是面试面到就这么说好了。。。= = 到时候有精力再回顾下吧。。。