[LeetCode]Container With Most Water
2017-06-08 07:48
357 查看
Description:
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.
解析:这道题的题意是,有n条竖线(隔板),求任意两条竖线与x轴组成的木桶的面积。实际上就是哪两个木板组成的面积最大。
这道题第一眼看去就抛去了暴力手法,太麻烦了,而且时间复杂度肯定不够,所以得找到技巧(规律)。这道题找出规律就好做了。
当你在纸上画图,然后慢慢观察的时候,你会发现:假设两条木板L,R(R是离L最远的一条木板)。如果L < R,那么对于L来说,他能组成最大的面积就是(R-L)乘L。其它的任何木板组成的面积都是(R-L-n)乘L。
这样的话,我们就不需要一个一个比较了,代码也就出来了。
code:
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.
解析:这道题的题意是,有n条竖线(隔板),求任意两条竖线与x轴组成的木桶的面积。实际上就是哪两个木板组成的面积最大。
这道题第一眼看去就抛去了暴力手法,太麻烦了,而且时间复杂度肯定不够,所以得找到技巧(规律)。这道题找出规律就好做了。
当你在纸上画图,然后慢慢观察的时候,你会发现:假设两条木板L,R(R是离L最远的一条木板)。如果L < R,那么对于L来说,他能组成最大的面积就是(R-L)乘L。其它的任何木板组成的面积都是(R-L-n)乘L。
这样的话,我们就不需要一个一个比较了,代码也就出来了。
code:
public int maxArea(int[] height) { if(height == null)return 0; int len = height.length-1; int index = 0; int area = 0; int temp = 0; while(index < len){ if(height[index] < height[len]){ temp = (len-index)*height[index]; index++; } else{ temp = (len-index)*height[len]; len--; } if(area < temp){ area = temp; } } return area; }
相关文章推荐
- leetcode-11 Container With Most Water
- [leetcode 11] Container With Most Water
- 【LeetCode】011 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, 解题报告
- 【LeetCode】【Python解读】Container with most water
- LeetCode题解——Container With Most Water
- [LeetCode] Container With Most Water
- leetcode(11) Container With Most Water
- leetcode:Container With Most Water
- 【LeetCode-面试算法经典-Java实现】【011-ContainerWithMostWater(容纳最多的水)】
- Leetcode -- Python --Container With Most Water
- [C++]LeetCode: 39 Container With Most Water
- LeetCode: Container With Most Water [Java]
- LeetCode Container With Most Water
- LeetCode No.11 Container With Most Water