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

[Leetcode] Container With Most Water

时间:2014-10-25 07:04:51      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

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: 

这道题起初我理解错了题意,以为是要找到选定数组中最小的来乘以(r-l)以此为基础来求组成的面积的最大值,其实这样是错的。

看了大神的解答后,这道题就是只看选中数组左边和右边的值,选择其中最小的那个来乘以(r-l),以此为基础来求组成的面积的最大值。

Solution : 2 pointers分别指向array的开头和结尾

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         int N=height.length;
 4         if(N<2)
 5             return 0;
 6      //   System.out.println("N==="+N);
 7         int maxarea=0;
 8         int l=0,r=N-1;
 9         while(l<r){
10             if(height[l]<height[r]){
11                 int temp=(r-l)*height[l];
12                 ++l;
13                 maxarea=Math.max(temp, maxarea);
14             }else{
15                 int temp=(r-l)*height[r];
16                 --r;
17                 maxarea=Math.max(temp, maxarea);
18             }
19         }
20         return maxarea;
21     }
22 }
 1 class Solution {
 2 public:
 3     int maxArea(vector<int> &height) {
 4         if (height.size() < 2) return 0;
 5         int i = 0, j = height.size() - 1;
 6         int maxarea = 0;
 7         while(i < j) {
 8             int area = 0;
 9             if(height[i] < height[j]) {
10                 area = height[i] * (j-i);
11                 //Since i is lower than j, 
12                 //so there will be no jj < j that make the area from i,jj 
13                 //is greater than area from i,j
14                 //so the maximum area that can benefit from i is already recorded.
15                 //thus, we move i forward.
16                 //因为i是短板,所以如果无论j往前移动到什么位置,都不可能产生比area更大的面积
17                 //换句话所,i能形成的最大面积已经找到了,所以可以将i向前移。
18                 ++i;
19             } else {
20                 area = height[j] * (j-i);
21                 //the same reason as above
22                 //同理
23                 --j;
24             }
25             if(maxarea < area) maxarea = area;
26         }
27         return maxarea;
28     }
29 };

 

[Leetcode] Container With Most Water

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4049639.html

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