[Leetcode] Container With Most Water

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)。

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