【leetcode】11-盛水最多的容器【C++】

题目如下:

【leetcode】11-盛水最多的容器【C++】_第1张图片

解题思路:

1、最简单的思路就是暴力求解,采用两次循环,时间复杂度为O(n^2)。

代码如下:

class Solution {
public:
    int maxArea(vector& height) {
        int length = height.size();
        int max = 0;
        int temp = 0;
        for(int i = 0; i < length; i++){
            for(int j = i+1; j < length; j++){
                temp = (j-i) * min(height[i], height[j]);
                if(temp > max)
                    max = temp;
            }
        }
        return max;
    }
};

2、对撞指针的方法

  • 两条线间的容积为(j - i) * min(height[i], height[j])
  • 首先,先取最左边直线和最右边直线,这种情况用 (0, n-1) 表示。
  • 下一步,考虑减少一个单位宽度的情况,有两种选择 (0, n-2) 和 (1, n-1) 。若高度 height[0] < height[n-1],即第0根线条是“短板”,那么 (0, n-2) 的容积肯定会比 (0, n-1) 的容积小(前者容积为height[0]乘以宽度,后者的“短板”肯定小于或等于height[0],且宽度变小),因此 (0, n-2) 的情况可以不用比较,下一步考虑 (1, n-1) 的情况。反之相同。
  • 依次类推。时间复杂度为O(n)。

代码如下:

class Solution {
public:
    int maxArea(vector& height) {
        int max = 0;
        int temp = 0;
        int left = 0;
        int right = height.size() - 1;
        for( ; left < right; ){
            temp = (right - left) * min(height[left], height[right]);
            if(temp > max)
                max = temp;
            if(height[left] < height[right]) //左边是“短板”
                left++;
            else //右边是“短板”
                right--;
        }
        return max;
    }
};

 

你可能感兴趣的:(leetcode算法题库)