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.

最简单的做法 : 直接遍历。 O(n ^ 2)。

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(height == null || height.length == 0) return 0;
 5         int len = height.length;
 6         int max = Integer.MIN_VALUE;
 7         for(int i = 0; i < len; i ++){
 8             for(int j = i + 1; j < len; j ++){
 9                 int sum = Math.min(height[i],height[j]) * (j - i);
10                 if(sum > max) max = sum;
11             }
12         }
13         return max;
14     }
15 }

超时。采用双指针来做。

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(height == null || height.length == 0) return 0;
 5         int len = height.length;
 6         int max = Integer.MIN_VALUE;
 7         int i = 0;
 8         int j = len - 1;
 9         while(i < j){
10             int sum = Math.min(height[i],height[j]) * (j - i);
11             if(sum > max) max = sum;
12             if(height[i] < height[j]) i ++;
13             else j --;
14         }
15         return max;
16     }
17 }

 

 

posted on 2013-10-17 12:31  Step-BY-Step  阅读(127)  评论(0编辑  收藏  举报

导航