leetcode第11题——**Container With Most Water

25 篇文章 0 订阅
25 篇文章 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.

思路

大意是数组下标i和非负数组值a[i] 组成一个坐标点(ia[i]),要找出两条纵线和x轴组成一个容器,使得容器能容纳最多水(不能“倾斜”该容器)。假设有(ia[i])和(ja[j])两个坐标(j > i),容积取决于min(a[i],a[j]) * (j - i)。
采用两层循环嵌套肯定是不能通过的,因为时间复杂度为o(n^2),输入大数组时严重超时。采用从两端向中间靠拢的办法,即 j - i 的值逐渐减小,这时高肯定要增大才可能取得更大的面积,按照这种思路不断更新i和j的值(i增大或者j减小),直到不满足i < j 时就能得到最优解。

代码

Python
class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        i = 0
        j = len(height) - 1
        res = 0
        while(i < j):
            res = max(res,min(height[i],height[j])*(j-i))
            if(height[i] < height[j]):
                k = i
                while (k < j) and (height[k] <= height[i]):
                    k += 1
                i = k
            else:
                k = j
                while (k > i) and (height[k] <= height[j]):
                    k -= 1
                j = k
        return res
Java
public class Solution {
    public int maxArea(int[] height) {
        int res = 0;
		int i = 0;
		int j = height.length - 1;
		int k;
		if (j < 1) return 0;
		//从两端向中间靠拢,找出比两端的线高的位置
		while (i < j){
			res = Math.max(res,Math.min(height[i], height[j])*(j - i));
			//左低右高,则找出最靠近i且比height[i]高的位置
			if (height[i] < height[j]){
				for(k = i;k < j && height[k] <= height[i];k++);
				i = k;
			}
			//右低左高,则找出最靠近j且比height[j]高的位置
			else{
				for(k = j;k > i && height[k] <= height[j];k--);
				j = k;
			}
		}
		return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值