leetcode: 11. Container With Most Water
来源:互联网 发布:演员知乎 编辑:程序博客网 时间:2024/06/14 08:23
题意:
输入n个数,每个数的值a[i]为该数的高(a[i] >= 0),其位置为该数的输入顺序(间隔为1),要求从这堆输入的数中找到两个高,使得这两个高之间的容器能装最多的水,注意:容器不能倾斜。
解题思路:
从离得最远的两个数入手,最远的两数拥有最大的宽度,然后当前的高为头尾两数的最小值,用宽高求出当前水容量ans。接着先从左往右寻找第一个比当前高要高的左下标i,再从右往左找比当前高的右下标j,再求当前两下标的水容量与ans相比,取最大者作为新的ans,直至i>=j时结束算法。其时间复杂度为O(n)。
class Solution {public: int maxArea(vector<int>& height) { int i = 0, j = height.size() - 1; int ans = 0, h; while(i < j){ h = min(height[i], height[j]); ans = max(h * (j - i), ans); while(height[i] <= h) i++; while(height[j] <= h) j--; } return ans; }};
0 0
- 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
- 11. Container With Most Water LeetCode
- 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 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
- spark机器学习库指南[Spark 1.3.1版]——决策树(decision trees)
- 5个Android开发中比较常见的内存泄漏问题及解决办法
- 开始的开始
- [Haskell on AIZU OJ] 0001-List of Top 3 Hills
- Android基础——适配安卓6.0新权限系统
- leetcode: 11. Container With Most Water
- Java Fundamental day05
- Codeforce div2 #401 E. Hanoi Factory
- 设计模式-元享模式
- Jquery——Day5(工具函数)
- Windows下安装TensorFlow,SoEasy
- Java 内存从分配到泄露
- JavaWeb学习(一)
- 杭电 2016