【LeetCode】Container With Most Water
来源:互联网 发布:台湾用大陆网络语言 编辑:程序博客网 时间:2024/06/03 17:02
Description
Container With Most Water
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.
Code
class Solution {public: int maxArea(vector<int>& height) { int left = 0, right = height.size() - 1; int maxV = 0, vol; while (left != right) { vol = (right - left) * min(height[right], height[left]); maxV = max(maxV, vol); if (height[left] < height[right]) // 左边那条线是短板,如果固定左边的板,让right--,那么新形成的容器一定会容积更小! ++left; else --right; } return maxV; }};
Review
这道题中也用了将两个变量分别初始化为区间头尾,根据一定条件将头向后移动,或将尾向前移动的方法。
题中要求的是最大容量,3Sum Closest要求的是最接近的值,或这种情况下可以用这个思路?
这道题中的限制条件是短板长度,既然有一边是短板了,不妨设左边是短板,那么右边再往左边靠近,得到的结果肯定比原来的结果还要小,干脆可以不考虑左边是短板的其他情况了,直接让左边的下一块板子当左板好了。
3Sum Closest中的限制条件是两个数的和。可以根据和target的大小关系来决定如何移动数字才能更靠近target一些。
0 0
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode-Container With Most Water
- Container With Most Water leetcode
- LeetCode - Container With Most Water
- LeetCode: Container With Most Water
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- LeetCode:Container With Most Water
- 赞!VC++编程学会使用D与R版通用调试输出功能,方便排错。
- 1022. Digital Library (30)PAT甲级
- The Letter Carrier's Rounds(UVa 814)
- stm32 移植cJson 注意free释放内存!!
- Download~!(南邮CTF)
- 【LeetCode】Container With Most Water
- ViewAnimator类及其子类的介绍
- java一条for循环打印多维数组
- UVA10954 :Add All(全部相加)
- [LeetCode]230. Kth Smallest Element in a BST
- java字符串转日期
- 修复公路 洛谷1111 并查集
- Webservice实践(七)CXF 与Spring结合+tomcat发布
- Android 简单定制一个视频播放器