LeetCode 11. Container With Most Water

题目:

给定n个非负整数a1 a2…,其中每个点表示坐标(i, ai)处的一个点。画出两条垂直线,使得直线i的两个端点分别为(i, ai)和(i, 0)。找出两条直线,这两条直线和x轴构成一个容器,使容器中含有最多的水。

注意:你不能倾斜容器,n至少是2。

即:

找到数组中两个数,使【其中较小的数*两数之间的距离】最大

Given n non-negative integers a1a2, ..., an , where each represents a point at coordinate (iai). nvertical lines are drawn such that the two endpoints of line i is at (iai) 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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Input: [1,8,6,2,5,4,8,3,7]     Output: 49

方法:

使【其中较小的数*两数之间的距离】最大,即其中较小的数需要更大、且两数之间的距离也要尽可能的大

使用maxA来记录当前最大距离,由于容器是两边分别有一个拦截,因此用两个loc来分别记录两边的位置,每次计算在距离loc1-loc2中的最大面积,具体方法为:

leftloc记录从0开始的位置,rightloc记录从nums.length-1开始的位置

计算当前【其中较小的数*两数之间的距离】,并与maxA进行比较,若大于,则替换;

比较leftloc和rightloc的数字大小,将较小数的位置往中间挪动一位

循环直到两位置重合

(使用这种方法,可以确保对于每个距离,所计算的面积都是最大的,不需要针对每个距离去遍历整个数组)

代码:

class Solution {
    public int maxArea(int[] height) {
        if(height.length<=1) {
            return 0;
        }
    	
        int leftLoc = 0;
        int rightLoc = height.length-1;
        int maxA = 0;
    	
        while(leftLoc<rightLoc) {
            int small = smaller(height[leftLoc], height[rightLoc]);
            // 计算面积
            int tempA = (rightLoc-leftLoc)*small;
            // 更新面积
            if(tempA>maxA) {
                maxA = tempA;
            }
    		
            // 移动
            if(small == height[leftLoc]) {
                leftLoc++;
            }else {
                rightLoc--;
            }
        }
        return maxA;
    }
    
    // 得到两个数中的较小数
    public int smaller(int a,int b) {
        if(a>b) {
            return b;
        }
        return a;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值