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
-
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()
的边界情况。
- 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!"
网友评论