leetcode题解-11. 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 and n is at least 2.

本题是为了寻找最大容积的两条直线。需要衡量的点主要是高度和宽度之间的权衡。首先我们想到的最简单的思路应该是使用暴力搜索法,使用两次遍历的方法分别对每个数搜索其最大容积。代码入下:

    public int maxArea(int[] height) {
        int max = 0;
        for(int i=0; i<height.length-1; i++){
            int tmp = height[i];
            for(int j=i+1; j<height.length; j++){
                max = Math.max(max, (j-i)*Math.min(tmp, height[j]));
            }
        }
        return max;
    }

但是这种方法会产生TLE,时间超出限制。所以我们相到下面的方法,分别从左右两边开始搜索,用max记录最大值,然后不断遍历。每次遍历的依据是看左右两边的值那个大,将小的移向下一位置。代码入下:

    public int maxArea1(int[] height){
        int max = 0, left=0, right=height.length-1;
        while(left < right){
            if(height[left] < height[right]){
                max = Math.max(max, (right-left)*height[left]);
                left ++;
            }else{
                max = Math.max(max, (right-left)*height[right]);
                right --;
            }
        }
        return max;
    }

上面这种方法客击败88。5%的用户,但是我们很显然还可以进行改进,就是每次都移动多次,这样可以省去计算最大值的时间,击败99。2%的用户。代码入下:

    public int maxArea2(int[] height) {
        int lo = 0;
        int hi = height.length - 1;
        int max = 0;
        while(lo < hi) {
            int min = Math.min(height[lo], height[hi]);
            max = Math.max(max, min * (hi - lo));
            while(lo <= hi && height[lo] <= min) lo++;
            while(lo <= hi && height[hi] <= min) hi--;
        }
        return max;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值