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

leet_11

时间:2016-01-26 12:22:39      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

n个非负的整数,a1,a2....an, 每一个都代表了一个坐标(i, ai). n条从点(i,ai) 到(i, 0)这样的垂直线。找到这样的两条线,和x轴形成一个容器,可以包含最多的水。

 

 

 
public static int maxArea(int[] height) {

if(null == height){
return 0;
}
int size = height.length;
int maxS = 0;

for(int i = 0; i < size; i++){
for(int j = i + 1;j < size; j++){
int maxSTemp = Math.min(height[i], height[j]) * (j - i);
if(maxSTemp > maxS){
maxS = maxSTemp;
}
}
}

return maxS;
}

public static int maxArea2(int[] height){

int max = 0;
int i=0, j=height.length-1;
while(i <= j){
int area = (j-i)*Math.min(height[i], height[j]);
max = Math.max(max, area);
if(height[j] >= height[i]){
i++;
}else{
j--;
}
}

return max;
}

 

 

 

Analysis

Initially we can assume the result is 0. Then we scan from both sides. If leftHeight < rightHeight, move right and find a value that is greater than leftHeight. Similarily, if leftHeight > rightHeight, move left and find a value that is greater than rightHeight. Additionally, keep tracking the max value.

技术分享

 

 

 

 

leet_11

标签:

原文地址:http://www.cnblogs.com/kniught-ice/p/5159569.html

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