Leetcode 11: Container With Most Water
来源:互联网 发布:当前大数据发展趋势 编辑:程序博客网 时间:2024/04/29 19:28
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.
Solution:
Use two pointers. Set start pointer at index 0 and end at height.length - 1. The height is always the smaller one of start and end and the width is end - start. The volume is height * width. Then to find a larger volume while narrowing the width, we should consider to increase the height after each move. So we should move the pointer with smaller value and try to update the volume until start equals to end.
Time complexity: O(n)
Space complexity: O(1)
<p>public class Solution { public int maxArea(int[] height) { int length = height.length; int volume = Integer.MIN_VALUE; if (height == null || length == 0) { return 0; } // Two pointers int i = 0; int j = length - 1; while (i < j) { int wid = j - i; int hei = Math.min(height[i], height[j]); volume = Math.max(volume, wid * hei); if (height[i] <= height[j]) { i++; } else { j--; } } return volume; }}</p>
- LeetCode 11: Container With Most Water
- leetcode 11 Container With Most Water
- Leetcode【11】:Container With Most Water
- [leetcode 11] Container With Most Water
- [leetcode 11] Container With Most Water
- LeetCode | #11 Container With Most Water
- leetcode.11---------Container With Most Water
- [LeetCode 11]Container With Most Water
- leetcode 11 Container With Most Water
- leetcode-11 Container With Most Water
- Container With Most Water - LeetCode 11
- [Leetcode 11, Medium] Container With Most Water
- LeetCode 11 - Container With Most Water
- leetcode 11 -- Container With Most Water
- #LeetCode OJ #11 Container With Most Water
- Leetcode #11 Container With Most Water
- leetcode-11Container With Most Water
- leetcode 11 -- Container With Most Water
- CPP-Templates
- 世恒百集易语言教程分享
- Leetcode243: Shortest Word Distance
- ios知识总结
- Linux_Rsync远程同步备份服务器
- Leetcode 11: Container With Most Water
- 从头认识java-13.8 类型擦除的问题与解决
- 99乘法表
- Python中通过多个字符分割(split)字符串的方法
- PHP学习1-Mac OS X环境配置和PHP介绍
- ES6学习——ES6背景介绍
- Xsolla与Ubisoft游戏Rainbow Six Siege 和刺客信条:辛迪加展开战略合作
- Ruby On Rails中REST API使用示例——基于云平台+云服务打造自己的在线翻译工具
- 举例数据库sqlite3的使用