1. 程式人生 > 實用技巧 >leetcode138container-with-water

leetcode138container-with-water

題目描述

給定n個非負整數a1,a2,…,an,其中每個數字表示座標(i, ai)處的一個點。以(i,ai)和(i,0)(i=1,2,3...n)為端點畫出n條直線。你可以從中選擇兩條線與x軸一起構成一個容器,最大的容器能裝多少水?
注意:你不能傾斜容器
例如: 輸入 [1,8,6,2,5,4,8,3,7]
輸出: 49

Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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. Note: You may not slant the container.


Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
示例1

輸入

複製
[1,8,6,2,5,4,8,3,7]

輸出

複製
49

class Solution {
public:
/**
*
* @param height int整型vector
* @return int整型
*/
int maxArea(vector<int>& height) {
// write code here
if (height.size()<2)//資料太少不能構成容器
return 0;
int i=0,j=height.size()-1;
int maxArea=0;
int tmpArea=0;
while (i<j){
tmpArea=min(height[i],height[j])*(j-i);
if (tmpArea>maxArea)
maxArea=tmpArea;
if (height[i]<height[j])
++i;
else
--j;
}
return maxArea;
}
};
class Solution {
public:
/**
*
* @param height int整型vector
* @return int整型
*/
int maxArea(vector<int>& height) {
// write code here
int l,r,Max=-9999;
for (l=0,r=height.size()-1;l<r;){
Max=max(Max,(r-l)*min(height[l],height[r]));
height[l]<height[r]?l++:r--;


}
return Max;
}
};
import java.util.*;


public class Solution {
/**
*
* @param height int整型一維陣列
* @return int整型
*/
public int maxArea (int[] height) {
// write code here
if (height.length<2){
return 0;

}
int left=0;
int right=height.length-1;
int maxV=0;
while (left<right){
int v=Math.min(height[left],height[right])*(right-left);
maxV=Math.max(v,maxV);
if (height[left]<height[right]){
left++;
}else {
right--;
}
}
return maxV;
}
}
#
#
# @param height int整型一維陣列
# @return int整型
#
class Solution:
def maxArea(self , height ):
# write code here
left=0
right=len(height)-1
V=0
while left<right:
V=max(V,min(height[left],height[right])*(right-left))
if height[left]<height[right]:
left+=1
else:
right-=1
return V