美文网首页
# 11 Container With Most Water[M

# 11 Container With Most Water[M

作者: BinaryWoodB | 来源:发表于2019-03-18 21:22 被阅读0次

Description

tags: Array, Two Pointer

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.


image.png

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution

class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0, r = height.size()-1;
        int V = 0;
        while (l < r) {
            int tempV = min(height[l], height[r]) * (r - l);
            V = max(tempV, V);
            if (height[l] <= height[r]) {
                l++;
            } else {
                r--;
            }
        }

        return V;
    }
};

Analysis

  • Time complexity: O(n)
  • Space complexity: O(1)

Points

  1. map::lower_bound(key), map::upper_bound(key)
  • map::lower_bound(key): 返回map中第一个大于或等于key的迭代器指针
  • map::upper_bound(key): 返回map中第一个大于key的迭代器指针
  • 若要拿到第一个不大于key的值,采用map::lower_bound(key)之后迭代器减一的方式,但要注意是否需要检查it == map.begin()的边界情况。
  1. String的拼接
string str1 = "hello ";
string str2 = "world!";
string res1 = str1 + str2; // res1 = "hello world!"
string str1 += str2; // str1 = "hello world!"
string res2 = str1.append(str2); // res2 = "hello world!"

相关文章

网友评论

      本文标题:# 11 Container With Most Water[M

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