盛水最多的容器

  算法   3分钟   126浏览   0评论

题目链接:https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47

题目描述

给定一个数组height,长度为n,每个数代表坐标轴中的一个点的高度,height[i]是在第i点的高度,请问,从中选2个高度与x轴组成的容器最多能容纳多少水

1.你不能倾斜容器

2.当n小于2时,视为不能形成容器,请返回0

3.数据保证能容纳最多的水不会超过整形范围,即不会超过2^31-1

数据范围:

0 <= height.length <= 10^5

0 <= height[i] <= 10^4

如输入的height为[1,7,3,2,4,5,8,2,7],那么如下图:

示例 1

输入:   [1,7,3,2,4,5,8,2,7]
返回值: 49

示例 2

输入:   [2,2]
返回值: 2

示例 3

输入:   [5,4,3,2,1,5]
返回值: 25

解题代码

import java.util.*;

public class Solution {
    public int maxArea (int[] height) {
        //排除不能形成容器的情况
        if (height.length < 2)
            return 0;
        int res = 0;
        //双指针左右界
        int left = 0;
        int right = height.length - 1;
        //共同遍历完所有的数组
        while (left < right) {
            //计算区域水容量
            int capacity = Math.min(height[left], height[right]) * (right - left);
            //维护最大值
            res = Math.max(res, capacity);
            //优先舍弃较短的边
            if (height[left] < height[right])
                left++;
            else
                right--;
        }
        return res;
    }
}

如果你觉得文章对你有帮助,那就请作者喝杯咖啡吧☕
微信
支付宝
  0 条评论