首页 > 其他 > 详细

【Leetcode】Container With Most Water

时间:2014-03-19 21:28:04      阅读:495      评论: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.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         int i = 0, j = height.size() - 1;
 5         int max_area = 0;
 6         while (i < j) {
 7             int area = (j - i) * min(height[j], height[i]);
 8             if (area > max_area) {
 9                 max_area = area;
10             }
11             if (height[i] <= height[j]) {
12                 ++i;
13             } else {
14                 --j;
15             }
16         }
17         return max_area;
18     }
19 };
View Code

容器的容积 C = min(ai, aj) * (j - i) (这里令 j > i) 。

从两边向中间夹逼扫描,所以第一个计算的是 j = n - 1, i = 0;

那么在夹逼的过程中,什么时候应该左指针向右,什么时候右指针向左呢?

回到容积计算公式,两边向中间扫描的过程中,因式中的(j - i)项一定是变小了,所以只有min(ai, aj)项增大才可能使得容积变大。所以应该当ai小的时候,右移左指针,aj小的时候左移右指针,检查下一个可能使得容积变大的容器。

【Leetcode】Container With Most Water,布布扣,bubuko.com

【Leetcode】Container With Most Water

原文:http://www.cnblogs.com/dengeven/p/3612169.html

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