leetcode 11 Container With Most Water

题意:

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 and n is at least 2.

 

思路:

暴力计算所有的ai,aj组合,计算过程利用如下性质:记录当前取得max_area时的max_start和max_end,固定ai,从右遍历aj时,aj必须大于max_end才有可能超过当前max_area。外层循环从左开始遍历ai,只有ai大于max_start才有可能超过max_area。

 

代码:

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         int max_area = 0;
 5         int max_end = 0;
 6         int max_start = 0;
 7         for(int i = 0;i < height.size();i++)
 8         {
 9             if(height[i] > max_start)
10             {
11                 for(int j = height.size() - 1;j > i;j--)
12                 {
13                     if(height[j] >= max_end)
14                     {
15                         int temp_area = (j - i) * min(height[i],height[j]);
16                         if(temp_area > max_area)
17                         {
18                             max_start = height[i];
19                             max_end = height[j];
20                             max_area = temp_area;
21                         }
22                     }
23                 }
24             }
25         }
26         return max_area;
27     }
28 };

这个解法比较low,时间复杂度应该还是o(n2),leetcode上o(n)的解法可参见:

https://leetcode.com/problems/container-with-most-water/solution/

posted on 2018-01-20 14:36  Tracy-mac  阅读(122)  评论(0编辑  收藏  举报

导航