leetcode—Container With Most Water
2017-12-19 19:37
369 查看
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 sum类似,利用夹逼准则,起始条件是一个索引在数组最左边,另外一个索引在数组最右边,从两边向中间靠拢,前进的准则是两个索引对应的数组值,如果左边的比较小,那么左边的像右滑动,如果右边的比较小,右边的像左滑动,因为这个装水是利用的短板原理,如果左边的比较小,滑动他,有可能会变大,但是滑动右边的,一定会变小,因为不是横坐标变小了就是纵坐标变小
Note: You may not slant the container and n is at least 2.
class Solution { public int maxArea(int[] height) { if(height==null || height.length<=0) return 0; int index1 = 0; int index2 = height.length-1; int max = 0; while(index1<index2){ max = Math.max(max,Math.min(height[index1],height[index2])*(index2-index1)); if(height[index1]<height[index2]){ index1++; }else{ index2--; } } return max; } }
和Two sum类似,利用夹逼准则,起始条件是一个索引在数组最左边,另外一个索引在数组最右边,从两边向中间靠拢,前进的准则是两个索引对应的数组值,如果左边的比较小,那么左边的像右滑动,如果右边的比较小,右边的像左滑动,因为这个装水是利用的短板原理,如果左边的比较小,滑动他,有可能会变大,但是滑动右边的,一定会变小,因为不是横坐标变小了就是纵坐标变小
相关文章推荐
- Container With Most Water(双指针)单调栈 leetcode11.
- [leetcode]Container With Most Water
- LeetCode--Container With Most Water
- Java [leetcode 11] Container With Most Water
- 刷LeetCode(11)——Container With Most Water
- 【leetcode】Container With Most Water
- leetcode-Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode:Container With Most Water 算法题详解
- leetcode--container_with_most_water
- LeetCode | #11 Container With Most Water
- LeetCode 011 Container With Most Water
- LeetCode之 Container With Most Water
- LeetCode 11 Container With Most Water
- [leetcode刷题系列]Container With Most Water
- LeetCode-Container With Most Water
- 【LeetCode】Container With Most Water
- [leetcode]Container With Most Water @ Python
- [Leetcode] Container With Most Water
- leetCode:Container With Most Water