leetcode做题总结,题目Container With Most Water------ 2012/01/08

本文介绍了一种求解两根竖直线间能盛放的最大水量问题的高效算法。该算法采用双指针技巧,从两端向中间逼近,通过避免不必要的比较,达到O(n)的时间复杂度。

这道题的思路很巧妙,从两边同时向中间移动,只有在遇到更高的杆的时候在进行计算,因为即使相同的杆长,距离缩短容积也会减少。


public int maxArea(int[] height) {
        if(height.length==0||height.length==1)return 0;
        int i=0,j=height.length-1;
        int ih=height[i],jh=height[j];
        int area=0,tmp=0;
        tmp=Math.min(ih,jh)*(j-i);
        if(tmp>area) area=tmp;
        while(i<j){
            
            if(ih<jh){
                while(height[i]<=ih&&i<j)i++;
                if(i<j)ih=height[i];
            }else{
                while(height[j]<=jh&&i<j)j--;
                if(i<j)jh=height[j];
            }
            if(i<j){
                tmp=Math.min(ih,jh)*(j-i);
                if(tmp>area) area=tmp;
            }
        }
        return area;
    }

Update 2015/08/23: 下面的代码思路一样,感觉比上面的写的好

public class Solution {
    /**
     * @param heights: an array of integers
     * @return: an integer
     */
    public int maxArea(int[] heights) {
        // write your code here
        if (heights.length == 0)
            return 0;
        int i = 0;
        int j = heights.length - 1;
        int max = 0;
        while (i < j){
            if (heights[i] < heights[j]){
                max = Math.max(max, heights[i] * (j - i));
                int tmp = heights[i];
                while (i < j && tmp >= heights[i])
                    i++;
            } else {
                max = Math.max(max, heights[j] * (j - i));
                int tmp = heights[j];
                while (i < j && tmp >= heights[j])
                    j--;
            }
        }
        return max;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值