[LeetCode]Container With Most Water
来源:互联网 发布:手机qq java 编辑:程序博客网 时间:2024/05/22 17:16
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.
在二维坐标系里,有一组长短不一垂直线段,用(i, ai)来表示每一条线,用任意两条线段和 x 轴可以组成一个容器,求容量最大的容器的容积。
简单的做法是采用二重循环遍历所有组合保利求解,找出最大的容器,但是这样做会导致超时。
更为合理的解法是,用两个指针分别指向数组的两端,当左边指针指向的数大于右边时,右边指针左移;当右边大于左边时,左边指针右移。重复此操作指导左边指针与右边指针会和。在遍历的过程中保存每次的容器容积,最后返回最大值即可。
class Solution {public: int maxArea(vector<int>& height) { int l = 0, r = height.size() - 1; int v = 0, max = 0;; while (l < r) { v = min(height[l], height[r]) * (r - l); if (v > max) { max = v;}if (height[l] < height[r]) {l++;} else {r--;}}return max; }};
阅读全文
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
- 11.11考试总结
- 数据结构部分考点整理
- hdoj 1727 Hastiness
- 多线程问题
- OpenMAX编程-数据结构
- [LeetCode]Container With Most Water
- Android短信验证码
- java使用axios.js的post请求后台时无法接收到参数的问题
- spring-cloud中config配置中心使用(基本使用)
- ionic购物车
- ValueError: too many values to unpack
- 【Java学习4.5】数组类型
- 数据结构实验之图论一:基于邻接矩阵的广度优先搜索遍历
- 重构培训课程后的一些感想