首页 > 其他 > 详细

LeetCode(11):Container With Most Water

时间:2016-01-26 21:34:40      阅读:268      评论: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.

题意:给定一个数组,数组中的元素代表一个木板的高度,i表示木板所处的位置,找到两个木板使两个木板之间的容量最大。

思路:采用双指针,left,right分别指向数组的首元素和末尾元素,因为容量的计算公式为(right - left)*min(height[left],height[right]),刚开始的时候是宽度最大(right-left)要想增大容量,宽度缩短了,所以,要选择高度较高的木板才能增大容量,这种情况下要保留木板高度大的一方,然后另一方移动。

代码:

public int min(int i,int j)
  {
    return i<j?i:j;
  }
public int maxArea(int[] height) {
        int cap = 0;
        int left = 0,right=height.length -1;
        while(left<right){
            int water =  min(height[left],height[right])*(right-left);
            if(water>cap) 
                cap = water;
             
            if(height[left]<height[right]){
                left ++;
            }else{
                right--;
            }
        }
        return cap;
    }

LeetCode(11):Container With Most Water

原文:http://www.cnblogs.com/Lewisr/p/5161406.html

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