码迷,mamicode.com
首页 > 其他好文 > 详细

Container With Most Water

时间:2015-10-06 14:06:00      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

 

题目:

  Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical 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.

 

思路:

   用两个指针分别从数组最左边 left 和最右边 right 同时往中间扫描,可以想到,倘若会出现更大的矩形,那么必定是出现在中间且高度比 left 和 right 中较短的高,所以可以得到如下关键扫描代码:

while (*left  <= high && left < right)  ++left;
while (*right <= high && left < right)  --right;

  其中, high 是 left 和 right 中较短的值,容积由最短的高度决定,只有两边都比最短的高的情况下,容积才有可能变大。

 

代码:

技术分享
 1 #define min(a,b) (a) > (b)? (b) : (a)
 2 int maxArea(int* height, int heightSize) {
 3     int water = 0, *left = height, *right = left + heightSize - 1;
 4     int tmp, high;
 5     while (left < right) {
 6         high = min(*left, *right);
 7         tmp = (right - left) * high;
 8         if (water < tmp)    water = tmp;
 9         while (*left  <= high && left < right)  ++left;
10         while (*right <= high && left < right)  --right;
11     }
12     return water;
13 }
Container With Most Water

 

Container With Most Water

标签:

原文地址:http://www.cnblogs.com/YaolongLin/p/4856595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!