Leetcode刷题11. 盛最多水的容器 | 您所在的位置:网站首页 › leetcode插件登录 › Leetcode刷题11. 盛最多水的容器 |
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。 示例: 输入:[1,8,6,2,5,4,8,3,7] 输出:49来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Solution { public int maxArea(int[] height) { // return maxAreaI(height); // return maxAreaII(height); return maxAreaIII(height); } //方法三:基于方法二优化,减少比较次数 //时间复杂度O(N),空间复杂度O(1) private int maxAreaIII(int[] height) { if (height == null || height.length == 0) { return 0; } int left = 0, right = height.length - 1; int maxArea = 0; while (left < right) { int h = Math.min(height[left], height[right]); maxArea = Math.max(maxArea, (right - left) * h); while (left < right && height[left] |
CopyRight 2018-2019 实验室设备网 版权所有 |