标签:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
代码如下:(方法一:超时)
1 public class Solution { 2 public int maxArea(int[] height) { 3 int max=0; 4 for(int i=0;i<height.length-1;i++) 5 { 6 int min=height[i]; 7 for(int j=i+1;j<height.length;j++) 8 { 9 if(min>height[j]) 10 min=height[j]; 11 if(min*(j-i)>max) 12 max=min*(j-i); 13 } 14 } 15 return max; 16 } 17 }
代码如下:(方法二:Accept)
1 public class Solution { 2 public int maxArea(int[] height) { 3 4 int left=0,right=height.length-1; 5 int max=Math.min(height[0],height[height.length-1])*(right-left); 6 7 while(left<right) 8 { 9 if(height[left]<=height[right]) 10 { 11 if(height[left]*(right-left)>max) 12 max=height[left]*(right-left); 13 left++; 14 } 15 else{ 16 if(height[right]*(right-left)>max) 17 max=height[right]*(right-left); 18 right--; 19 } 20 } 21 return max; 22 } 23 }
标签:
原文地址:http://www.cnblogs.com/ghuosaao/p/5481681.html