Leetcode题解:11. Container With Most Water
来源:互联网 发布:linux test -e 编辑:程序博客网 时间:2024/05/22 11:43
Leetcode题解:11. Container With Most Water
难度:Medium
题目:
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.
中文简述
给你一串数组a1,a2….an,其中ai表示坐标系中的 (i,ai)即i位置上的垂直高度,其中每两条竖直的线都能组成一个容器来装水,问其中装水最多的容器的容积是多少
思路
其实根据描述,我们知道容积V=(j-i)*min{ai,aj} (i < j)
所以最简单的一个思路就是暴力找出所有容器的容积,然后比较他们的大小,这样做的时间复杂度为O(n^2)
转换一下思路,由于容器的容积取决于两边相隔距离和两边中较短边的高度。我们可以用贪心算法去化简:
①从最远的一对容器边找起,即i=0,j=n;
②从较短边开始向内搜索,计算容积比较大小。重复②直到i=j;
于是我们就能得到一个时间复杂度为O(n)的算法
class Solution {public: int maxArea(vector<int>& height) { int l=0, r=height.size()-1; int maxsize = 0; while(l<r){ if(height[l]<height[r]){ maxsize = (maxsize<(r-l)*height[l]? (r-l)*height[l]: maxsize); l++; } else{ maxsize = (maxsize<(r-l)*height[r]? (r-l)*height[r]: maxsize); r--; } } return maxsize; }};
0 0
- 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
- atom使用快捷键
- [.NET] 打造一个很简单的文档转换器 - 使用组件 Spire.Office
- 天天团购 切底去除版权、删除版权
- C++11用两个线程轮流打印整数
- Memcached远程代码执行漏洞预警与检测修复
- Leetcode题解:11. Container With Most Water
- kubernetes1.4 基础篇:Learn Kubernetes 1.4 by 6 steps(1):概要
- 多线程编程
- 【14.94%】【codeforces 611E】New Year and Three Musketeers
- Hello world !
- Python 两个图形小程序
- 关于点击事件的触发器具体使用方法
- noip2012同余方程 (拓展欧几里得)
- 吐槽一下CSDN的OpenAPI