首页 > 其他 > 详细

LeetCode - Container With Most Water

时间:2014-02-09 16:09:01      阅读:432      评论:0      收藏:0      [点我收藏+]

Container With Most Water

2014.2.8 21:37

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.

Note: You may not slant the container.

Solution:

  A very plain solution is to do a O(n^2) scan, check out every pair of (a[i], a[j]) and find out the maximal min(a[i], a[j]) * (i - j).

  You know this is far from satisfactory, so let‘s try to find an O(n) solution.

  Suppose we‘ve got a candidate pair (a[x], a[y]), the result is min(a[x], a[y]) * (x - y). If it is currently the optimal candidate, there cannot be any a[k] >= a[x] left of a[x], or any a[k] >= a[y] right of a[y], think about why.

  If we are to find a better solution (a[x‘], a[y‘]), it must lie within the interval (x, y), and satify the condition (a[x‘] > a[x] && a[y‘] >= a[y]) or (a[x‘] >= a[x] && a[y‘] > a[y]).

  This means we can scan the array from both ends in one pass, and end the algorithm when both iteraotors meet in the middle.

  Time complexity is O(n), space complexity is O(1).

Accepted code:

bubuko.com,布布扣
 1 // 1CE, 1AC, good.
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int maxArea(vector<int> &height) {
 8         if (height.empty()) {
 9             return 0;
10         }
11         
12         int ll, rr, kk, result;
13         
14         ll = 0;
15         rr = (int)height.size() - 1;
16         result = 0;
17         while (ll < rr) {
18             result = max(result, min(height[ll], height[rr]) * (rr - ll));
19             if (height[ll] < height[rr]) {
20                 kk = ll + 1;
21                 while (kk < rr && height[kk] <= height[ll]) {
22                     ++kk;
23                 }
24                 ll = kk;
25             } else {
26                 kk = rr - 1;
27                 while (kk > ll && height[kk] <= height[rr]) {
28                     --kk;
29                 }
30                 rr = kk;
31             }
32         }
33         
34         return result;
35     }
36 };
bubuko.com,布布扣

LeetCode - Container With Most Water

原文:http://www.cnblogs.com/zhuli19901106/p/3541097.html

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