首页 > 其他 > 详细

[Leetcode] Container With Most Water

时间:2018-01-30 14:24:19      阅读:204      评论:0      收藏:0      [点我收藏+]

Container With Most Water 题解

题目来源:https://leetcode.com/problems/container-with-most-water/description/


Description

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical 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 and n is at least 2.

Solution


class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0;
        int low = 0, high = height.size() - 1;
        int tempHeight;
        while (low < high) {
            tempHeight = min(height[low], height[high]);
            res = max(res, (high - low) * tempHeight);
            // 要找到low和high之间其它可能的高度,
            // 必须高于当前最低高度,才有可能会有更大容积
            while (low < high && height[low] <= tempHeight) 
                low++;
            while (low < high && height[high] <= tempHeight)
                high--;
        }
        return res;
    }
};

解题描述

这道题题意是,给出一个数组height,包含n个元素,其中每个数据代表平面直角坐标系上一个点(i, height[i]),由点向x轴做垂线,在所有垂线中选出2条,与x轴可以构成一个容器,所有构成的容器中能装最多多少水。也就是找到一组数据,其“容积”为

res = abs(i - j) + min(height[i], height[j])

最大。

一开始我想到的办法是2层循环的暴力破解,但是提交上去就一直超时,看了评论区之后发现用从两边向中间夹逼的办法能把时间复杂度从暴力破解的O(n^2)降到O(n)。

[Leetcode] Container With Most Water

原文:https://www.cnblogs.com/yanhewu/p/8384008.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!