leetcode——Container With Most Water

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

         一开始没看懂题目,后来查了网上答案,大概意思是:x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an。找出两条线段,使他们和x轴围成的面积最大。面积公式是 Min(ai, aj) X |j - i|

思路1:

注意到面积大即容积大,面积由最短高度来决定,要求返回的是最大面积。

一开始想到的就是双重循环,遍历i,j, 但是时间复杂度是O(n²),会超时

class Solution {
public:
    int maxArea(vector<int> &height) {
        // 宽乘以最短木板长度就是最大面积
        // 宽是1,2,3....
        // 时间复杂度O(n²)
        int start(0), end(1); // 记录起始木板的横坐标,两个之差为宽
        int area(INT_MIN);
        for(start = 0; start != height.size(); start++){
            for(end = start+1; end != height.size(); end++){
                area = max(area, min(height[start], height[end]) * (end - start));
            }
        }
        return area;
    }
};

image

思路2:

看了大神的答案.

容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以我们从长度最长时开始递减,然后寻找更高的线来更新候补.

class Solution {
public:
    int maxArea(vector<int> &height) {
        // 容积由面积决定
        // 面积由短木板高度决定
        // 当宽度减少时,短木板的高度应该增加,才能保证面积的增加,因此要找到比短木板的高度高的木板
        // 返回最大面积
        int l(0), r(height.size()-1), area(INT_MIN);
        while(l < r){
            area = max(area, min(height[l], height[r]) * (r-l));
            if(height[l] <= height[r]) l++;
            else r--;
        }
        return area;
    }
};
原文地址:https://www.cnblogs.com/skysand/p/4298102.html