【LeetCode】Container With Most Water
2013-10-12 10:22
288 查看
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.
这题有点像直方图中最大矩形面积,刚开始就看错了,结果不一样,O(n)的算法是看了网上一个大牛的:
来一个java的,最近在研究java:
..., 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.
这题有点像直方图中最大矩形面积,刚开始就看错了,结果不一样,O(n)的算法是看了网上一个大牛的:
class Solution { public: int maxArea(vector<int> &height) { // Note: The Solution object is instantiated only once and is reused by each test case. int size = height.size(); int ld = 0, rd = size - 1; int res = 0; if(size <= 1) return 0; while(ld < rd) { int h = height[ld] < height[rd] ? height[ld] : height[rd]; res = max(res,h*(rd-ld)); if(height[ld] < height[rd]) ld++; else rd--; } return res; } };
来一个java的,最近在研究java:
public class Solution { public int maxArea(int[] height) { // Note: The Solution object is instantiated only once and is reused by each test case. int size = height.length; int ld = 0, rd = size - 1; int res = 0; while(ld < rd) { int h = height[ld] < height[rd] ? height[ld] : height[rd]; res = Math.max(res,h*(rd-ld)); if(height[ld] < height[rd]) ld++; else rd--; } return res; } }
相关文章推荐
- LeetCode: Container With Most Water 题解
- leetcode (11) - Container With Most Water
- Container With Most Water(双指针)单调栈 leetcode11.
- 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 11 Container With Most Water (C,C++,Java,Python)
- leetcode-11-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]011-Container With Most Water
- [leetcode] Container With Most Water
- [LeetCode]#11 Container With Most Water
- 11【Leetcode】 Container With Most Water
- LeetCode: Container With Most Water