leet_11

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leet_11相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

leet_15

leet_14 Longest Common Prefix

Leet code problem 7: reverse integer digit

leet code 54. 螺旋矩阵

leet code 54. 螺旋矩阵

leet code Two Sum