Leetcode题解-11. Container With Most Water
来源:互联网 发布:试用平台源码 编辑:程序博客网 时间:2024/06/10 14:06
Leetcode题解-11. 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.
思路
一种简单的想法就是用两重遍历,那时间复杂度就是O(n^2)了,比较简单这里就不再赘述了。
这里用另外一种方法:用max表示最大容量,开始时用i指向数组头,j指向数组尾,求出i、j之间的容量min{height[i], height[j]}·(j-i),与max比较,max比当前所求容量小则将当前容量赋值给max。然后倘若height[i]小于height[j],则i++,反之j- -。重复上述过程直至i等于j,返回max。这里时间复杂度为O(n).
证明:假设height[i] < height[j],container1 =height[i]·(j-i),则container1 > container2(container2 = height[k]·(k-i)(i < k < j)),所以不必要考虑container2,所以将i++。反之height[i] > height[j]同样的道理,只需要将j- -。
代码
int maxArea(vector<int>& height) { int i = 0, j = height.size() - 1; int max = 0; while(i != j){ int min = 0; int cur = 0; if(height[i] <= height[j]){ min = height[i]; cur = min * (j-i); i++; } else{ min = height[j]; cur = min * (j-i); j--; } if(max < cur) max = cur; } return max; }
- 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】【Python题解】Container with most water
- leetcode题解||Container With Most Water问题
- LeetCode题解:Container With Most Water
- LeetCode题解-11-Container With Most Water
- leetcode题解Java | 11. Container With Most Water
- [模拟]LeetCode 11. Container With Most Water 题解
- LeetCodet题解--11. Container With Most Water
- 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
- html-3
- iOS 字符串路径相关Api
- java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException 异常解决方案
- Dockerfile编写总结
- 元素垂直居中的几种方法
- Leetcode题解-11. Container With Most Water
- 阿里云前端周刊
- Java后台框架篇--Spring与Restful风格API接口开发
- iPhone X电池性能如何:双电池与无线充电的博弈
- 第四周:310. Minimum Height Trees(最小高度树)
- input输入框的宽度自适应
- mysql字符串处理
- 通过继承Thread类的方式创建两个线程
- 半透明背景Activity实现AlertDialog弹窗效果