算法系列——Container With Most Water
来源:互联网 发布:linux一键安装lamp 编辑:程序博客网 时间:2024/05/21 19:42
题目描述
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.
解题思路
用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。
原因:当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, …)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。
程序实现
public class Solution { public int maxArea(int[] height) { if(height==null||height.length<2) return 0; int left=0; int right=height.length-1; int maxVal=0; while(left<right){ int curVal=(right-left)*Math.min(height[left],height[right]); if(curVal>maxVal) maxVal=curVal; if (height[left] < height[right]) left++; else right--; } return maxVal; }}
阅读全文
0 0
- 算法系列——Container With Most Water
- 每日一道算法题——Container with Most Water
- LeetCode算法题——11. Container With Most Water
- LeetCode算法题——Container With Most Water
- LeetCode算法问题6 —— Container With Most Water
- 数据结构与算法[LeetCode]—Container With Most Water
- 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
- Container With Most Water —— Leetcode
- leetcode——Container With Most Water
- LeetCode——Container With Most Water
- <11>——Container With Most Water
- LeetCode——Container With Most Water
- LeetCode11——Container With Most Water
- elasticsearch详解(一)——es是什么、能做什么?
- 基于unity射线的个人理解(一)
- web前端图片懒加载
- Just a Hook
- 震惊!!!平衡二叉树居然还有这种学习方法!!
- 算法系列——Container With Most Water
- 2017.8.7 hash测试 与数字签名
- TensorFlow培训
- IDEA搭建SpringBoot集成Jsp的辛酸历程
- 高德获取ip地理位置
- Qt国际化——多语言翻译时值得注意的一个编程问题
- java网络编程面试题
- php读取本地文件常用函数
- SQL查询和优化(六)