美文网首页
11.Container With Most Water

11.Container With Most Water

作者: yangqi916 | 来源:发表于2016-12-15 22:39 被阅读0次

复杂度

时间 O(N) 空间 O(N)

思路

最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,把边往中间移,看能不能遇到更大的边长。只有更高的边才可能有更大的面积。

  • 如果是较高的边往里面移,发现,无论边变长了还是短了,都不影响面积,因为较短边是不会变的。而底还变小了,所以面积变小。 所以唯一的变大方法便是把较短边往里移,看看能不能找到更高的。

注意

如果将较短的边向中间移后,新的边还更短一些,其实可以跳过,减少一些计算量

#include<vector>
#include<algorithm>
#include<cstdio>
#include <unordered_map>
#include <cmath>
#include <string>
#include <set>
using namespace std;

class Solution {
private:
    int min(int a, int b)
    {
        return a<b? a:b;
    }
    
    int max(int a, int b)
    {
        return a>b? a:b;
    }

public:
    int maxArea(vector<int>& height) {
        int size = (int)height.size();
        
        if (size <= 1) return 0;
        
        int left = 0, right = size - 1;
        
        int maxS = 0;
        
        while (left < right)
        {
            maxS = max(maxS, (right - left) * min(height[left], height[right]));
            
            if (height[left] < height[right])
            {
                int temp = left;
                
                while (temp < right && height[temp] <= height[left])
                    temp++;
                left = temp;
            }
            else
            {
                int temp = right;
                
                while (temp > left && height[temp] <= height[right])
                    temp--;
                right = temp;
            }
        }
        
        return maxS;
        
    }
};

相关文章

网友评论

      本文标题:11.Container With Most Water

      本文链接:https://www.haomeiwen.com/subject/qlggmttx.html