[leetcode] 11. Container With Most Water
2016-03-07 15:16
330 查看
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.
这道题是找最大容器,题目难度为Medium。
双层循环暴力比对的方法估计会超时,就不尝试了。
我们拿a1和an组成的容器作为初始容器,容器容积为min(a1,an)*(n-1),把(n-1)记为长,min(a1,an)记为高。计算容器容积时要考虑到长的因素,以min(a1,an)为高的其他任何容器都不会比初始值大,因为其他容器高最大为min(a1,an),而长必定小于(n-1),所以a1和an中小的那条线在后续比较中就可以不考虑了。如果min(a1,an)==a1,我们继续查看a2和an组成的容器,否则查看a1和an-1组成的容器,同时更新最大容器值。依照这样的策略逐步缩小范围,最终就得到了最大容器。具体代码:class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int maxWater = 0;
while(l < r) {
maxWater = max(maxWater, min(height[r],height[l])*(r-l));
if(height[l] < height[r]) ++l;
else --r;
}
return maxWater;
}
};
..., 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.
这道题是找最大容器,题目难度为Medium。
双层循环暴力比对的方法估计会超时,就不尝试了。
我们拿a1和an组成的容器作为初始容器,容器容积为min(a1,an)*(n-1),把(n-1)记为长,min(a1,an)记为高。计算容器容积时要考虑到长的因素,以min(a1,an)为高的其他任何容器都不会比初始值大,因为其他容器高最大为min(a1,an),而长必定小于(n-1),所以a1和an中小的那条线在后续比较中就可以不考虑了。如果min(a1,an)==a1,我们继续查看a2和an组成的容器,否则查看a1和an-1组成的容器,同时更新最大容器值。依照这样的策略逐步缩小范围,最终就得到了最大容器。具体代码:class Solution {
public:
int maxArea(vector<int>& height) {
int l = 0, r = height.size()-1;
int maxWater = 0;
while(l < r) {
maxWater = max(maxWater, min(height[r],height[l])*(r-l));
if(height[l] < height[r]) ++l;
else --r;
}
return maxWater;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解