leetCode 11.Container With Most Water (数轴上容器) 解题思路和方法

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.


思路:题目意思是数轴上有一系列线,求最大两条线中间的面积。这个的case因为数量量非常大,用穷举和排序的方法效率太低。

最后使用双线扫描,线性时间内解决。其思想在注释上已解释。

具体代码如下:

public class Solution {
    public static int maxArea(int[] height) {
        int len = height.length;
        int k = 0;
        int i = 0;
        int j = len - 1;
        int max= 0;
        int min = 0;
        //从开头和结尾双线扫描,i,j为位置指针
        while(i < j){
        	min = Math.min(height[i], height[j]);
        	//更新最大面积
            if(max < min*(j - i)){
            	max = min*(j-i);
            }
            //从位置指针的小者计算
            if(height[i] < height[j]){
            	k = i;
            	//如果右边的边比height[i]小,则右边的边肯定不是最大面积者
            	//因为其面积height[k]-height[j]肯定小于height[i]-height[j]
            	//故可直接跳过,只有当height[k] > height[i]时才跳出循环与max比较
            	while(k < j && height[k] <= height[i]){
            		k++;
            	}
            	i = k;
            }else{
            	k = j;
            	//与上同
            	while(i < k && height[k] <= height[j]){
            		k--;
            	}
            	j = k;
            }
        }
        return max;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值