首页 > 其他 > 详细

LeetCode: Container With Most Water 解题报告

时间:2014-10-28 19:30:00      阅读:229      评论:0      收藏:0      [点我收藏+]

Container With Most Water
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.

SOLUTION 1:

采用2个指针一个在左一个在右,计算『桶』可以容纳的水。如果左边低,则左指针右移(试图看可不可以找到更高的bar),反之左移右指针 

bubuko.com,布布扣
 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         if (height == null) {
 4             return 0;
 5         }
 6         
 7         int left = 0;
 8         int right = height.length - 1;
 9         int maxArea = 0;
10         
11         while (left < right) {
12             int h = Math.min(height[left], height[right]);
13             int area = h * (right - left);
14             maxArea = Math.max(maxArea, area);
15             
16             if (height[left] < height[right]) {
17                 // 如果左边界比较低,尝试向右寻找更高的边界
18                 left++;
19             } else {
20                 // 如果右边界比较低,尝试向左寻找更高的边界
21                 right--;
22             }
23         }
24         
25         return maxArea;
26     }
27 }
View Code

代码:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/twoPoints/MaxArea.java

LeetCode: Container With Most Water 解题报告

原文:http://www.cnblogs.com/yuzhangcmu/p/4057252.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!