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

Container With Most Water

时间:2015-09-02 07:04:48      阅读:172      评论: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.

Note: You may not slant the container.

 

Analyse: Set two variables, left and right to represent the leftmost and rightmost element respectively. We increase left and decrease right gradually. If the moving items are smaller than height[left] and height[right], then we don‘t need to change the value of left and right. Otherwise, we change the values and compare the area with the former computed one. 

Runtime: 32ms.

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         if(height.empty()) return 0;
 5         
 6         int left = 0, right = height.size() - 1;
 7         int result = 0;
 8         while(left <= right){
 9             int h = min(height[left], height[right]);
10             result = max(result, h * (right - left));
11             
12             if(height[left] > height[right]){
13                 int index = right;
14                 while(left <= index && height[index] <= height[right])
15                     index--;
16                 right = index;
17             }
18             else{
19                 int index = left;
20                 while(index <= right && height[index] <= height[left])
21                     index++;
22                 left = index;
23             }
24         }
25         return result;
26     }
27 };

 

Container With Most Water

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4777511.html

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