[ LeetCode ] #11. Container With Most Water(最大容器 C++ & Python)

题目:11. Container With Most Water

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 iis 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 and n is at least 2.

题意:

给一个包含非负整数的数组,以数组中元素的值为容器的高,两个数组下标距离为长,求矩形容器的最大面积。输入数组最少包含两个数。

分析:

  1. 第一种思路:暴力遍历所有情况,输出最大值。实现见Code1.
  2. 第二种思路:通过观察可以看出,矩形容器的高度总是被最短的那个数限制到,因此,可以改变较小的一端。实现见Code2.

 

Code1 & C++

class Solution {
public:
    int maxArea(vector<int>& height) {
        	int max=0, len=height.size();
	for(int i=0;i<len-1; ++i){
		for(int j=i+1; j<len; ++j){
			int tmpHeight = height[i]>height[j]?height[j]:height[i];
			if(max < tmpHeight*(j-i)){
				max = tmpHeight *(j-i);
			} 
		}
	}
	return max;
    }
};

结果:

Runtime: 1520 ms, faster than 18.17% of C++ online submissions for Container With Most Water.

Memory Usage: 10 MB, less than 64.39% of C++ online submissions for Container With Most Water.

Code2 & C++

auto s=height.begin(), e = height.end()-1;
	int maxA = 0;
	while(s!=e){
		int tmp,h=e-s;
		if(*s<*e){
			tmp = *s;
			++s;
		}else{
			tmp = *e;
			--e;
		}
		maxA = max(maxA, tmp*h);
	}
	return maxA;

这里 设置了两个端点分别位于起始处和终止处。两端同时向中间较大的值靠拢。

结果

Runtime: 20 ms, faster than 98.54% of C++ online submissions for Container With Most Water.

Memory Usage: 10.1 MB, less than 17.25% of C++ online submissions for Container With Most Water.

Code2 & Python

class Solution:
    def maxArea(self, a: 'List[int]') -> 'int':
        i,j = 0, len(a)-1
        maxA, tmp = 0, 0

        while i<j:
            if a[i]>a[j]:
                tmp = a[j]
                j-=1
            else:
                tmp = a[i]
                i+=1
            area = tmp *(j-i+1)
            maxA = area if area>maxA else maxA
        return maxA

结果:

Runtime: 48 ms, faster than 99.77% of Python3 online submissions for Container With Most Water.

Memory Usage: 13.5 MB, less than 90.54% of Python3 online submissions for Container With Most Water.

第二种方法 动画展示,能加形象的理解这一过程。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值