public class Solution
    {
        //public int MaxArea(int[] height)
        //{
        //    var max = 0;
        //    for (int i = 0; i < height.Length; i++)
        //    {
        //        for (int j = 0; j < height.Length; j++)
        //        {
        //            if (i == j)
        //            {
        //                continue;
        //            }
        //            var min = Math.Min(height[i], height[j]);
        //            var dif = Math.Abs(i - j);
        //            var product = min * dif;
        //            max = Math.Max(max, product);
        //        }
        //    }
        //    return max;
        //}
        public int MaxArea(int[] height)
        {
            int max = int.MinValue;
            for (int i = 0, j = height.Length - 1; i < j;)
            {
                if (height[i] > height[j])
                {
                    max = Math.Max(max, height[j] * (j - i));
                    j--;
                }
                else
                {
                    max = Math.Max(max, height[i] * (j - i));
                    i++;
                }
            }
            return max;            
        }
    }

 下面这个解决方案算是一种搞笑吧,夸张的6796ms,居然也能AC!

 1 class Solution:
 2     def findTopTwoNum(self,height):
 3         top1 = -1
 4         top1_index = -1
 5 
 6         top2 = -1
 7         top2_index = -1
 8         for i in range(len(height)):
 9             if top1 < height[i]:
10                 top1 = height[i]
11                 top1_index = i
12 
13         for i in range(len(height)):
14             if i != top1_index and top2 < height[i]:
15                 top2 = height[i]
16                 top2_index = i
17                 
18         return top1_index,top2_index 
19 
20     def maxArea(self, height: 'List[int]') -> 'int':
21         #在height中找最大的两个数字,以及这两个数字的坐标
22         left,right = self.findTopTwoNum(height)
23 
24         ma = min(left,right) * (right - left)
25         for i in range(left,-1,-1):
26             for j in range(right,len(height)):
27                 area = min(height[i],height[j]) * (j-i)
28                 if area > ma :
29                     ma = area
30         return ma
31         

 

Java版本:

 1 class Solution {
 2     public int maxArea(int[] height) {
 3         int l = height.length;
 4         int i=0;
 5         int j=l-1;        
 6         int result = 0;
 7         while(i < j){
 8             int maxArea = Math.min(height[i],height[j]) * (j - i);
 9             result = Math.max(result,maxArea);
10             if(height[i] <= height[j]){
11                 i++;
12             }else{
13                 j--;
14             }
15         }
16         return result;
17     }
18 }

 

posted on 2018-10-04 21:42  Sempron2800+  阅读(155)  评论(0编辑  收藏  举报