lintcode-medium-Container with Most Water
2016-03-16 12:09
411 查看
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate
Given
思路:
用左右两个指针向中间移动,记录任一时刻的截面积,如果比之前的结果大,就更新结果
当左边高度大于右边事,如果移动左边,则接下来的结果不会大于现在的结果,所以要移动右边,反之亦然,结论是总是移动高度较小的边
(i, ai). nvertical 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.
Given
[1,3,2], the max area of the container is
2.
思路:
用左右两个指针向中间移动,记录任一时刻的截面积,如果比之前的结果大,就更新结果
当左边高度大于右边事,如果移动左边,则接下来的结果不会大于现在的结果,所以要移动右边,反之亦然,结论是总是移动高度较小的边
public class Solution { /** * @param heights: an array of integers * @return: an integer */ public int maxArea(int[] heights) { // write your code here if(heights == null || heights.length == 0) return 0; int left = 0; int right = heights.length - 1; int result = 0; while(left < right){ int area = (right - left) * Math.min(heights[left], heights[right]); if(area > result) result = area; if(heights[left] > heights[right]) right--; else left++; } return result; } }
相关文章推荐
- inotify-tools使用
- 如何解决 You have new mail in /var/spool/mail/root
- 3月3号周练——2015 Multi-University Training Contest 7
- 杭电ACM1021裴波纳挈数AGAIN
- process launch failed: security 以及证书过期处理
- 发现大量的TIME_WAIT解决办法
- kafka.common.FailedToSendMessageException: Failed to send messages after 3 tries.
- HDU Fibonacci Again
- Error:(26, 13) Failed to resolve: com.squareup.picasso:picasso:2.5.2 的解决
- OpenCV Stitching_detailed 详解
- 直接插入排序(Straight Insertion Sort)
- fresh air项目记录1
- poj 1804 Brainman(归并排序求逆序对)
- 线程间协作:wait、notify、notifyAll
- Aizu - 0189 Convenient Location(floyd)
- 217. Contains Duplicate
- MyBaits
- 十四步实现拥有强大AI的五子棋游戏
- 设计模式之责任链模式(ChainOfResponsibility)&正反顺逆链处理
- 06.RAID