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

Given n non-negative integers a1 , a2 , ..., an , where each represents a point at coordinate (i, ai ). nvertical 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.
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
            
            
          
原文地址:https://www.cnblogs.com/hrnn/p/13402236.html