首页 > 其他 > 详细

LeetCode第11题 盛水最多的容器

时间:2019-01-11 20:35:51      阅读:158      评论:0      收藏:0      [点我收藏+]
/*
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。*/

思路: 类似于木桶效应.
   每次移动较短的线,保持长线不动.(如果短线不动而长线动,容量减小(y没有增大反而x变小))
    记录最大值.

 1 class Solution11 {
 2 
 3   public int maxArea(int[] height) {
 4     int right = height.length - 1;
 5     int left = 0;
 6     int max = Integer.MIN_VALUE;
 7     while (left < right) {
 8       int area = Math.min(height[right], height[left]) * (right - left);
 9       max = Math.max(max, area);
10       if (height[left] < height[right]) {
11         left++;
12       } else {
13         right--;
14       }
15     }
16     return max;
17   }
18 }

 

LeetCode第11题 盛水最多的容器

原文:https://www.cnblogs.com/rainbow-/p/10257101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!