[LeetCode]Container With Most Water
来源:互联网 发布:word数据透视表 编辑:程序博客网 时间:2024/05/21 10:39
[LeetCode]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.
解题思路
- 用两个变量记录水桶的左边缘(left)和右边缘(right);
- 达到最优解时,两个边缘都必须满足一个至关重要的条件——边缘外侧不能有更高的木板,因为如果外侧有更高的木板,则可用更高的木板作为边缘替换当前的边缘木板,得到更大的容积;
- 所以可以考虑从两端向中间遍历,如果遍历的当前的木板的外侧有更高的木板,则可以直接跳过不必计算面积;
代码
public class ContainerWithMostWater { public static int maxArea(int[] height) { int left = 0; int right = height.length-1; int area = 0; int leftmax = left, rightmax = right; while(left < right) { int temparea = (right-left) * (Math.min(height[left], height[right])); if(temparea > area) area = temparea; if(height[left] > height[leftmax]) leftmax = left; if(height[right] > height[rightmax]) rightmax = right; if(height[left] < height[right]) { left++; while(height[left] < height[leftmax]) left++; } else { right--; while(height[right] < height[rightmax]) right--; } } return area; } public static void main(String[] args) { int[] height = {1, 2, 1}; System.out.println(maxArea(height)); }}
感想
啊。。。。代码小弱的第一篇技术相关博客@@#¥%……&*
medium难度的题感觉想清楚了写起来还是很快的木哈哈
本题说到底还是一个“双指针”问题,双指针的使用可以将原本需要两层嵌套循环的问题降低到只用一次循环即可解决。
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
- 成为java大牛必须知道的25点
- 【GLSL教程】(三)在OpenGL中向shader传递信息
- android最全面 笔试题71道题 详解
- 在ubuntu-12.04.3下搭建编译android4.4源代码-编译源码部分问题及sdk编译
- Java80商城系统第五节-前端商品展示
- [LeetCode]Container With Most Water
- 个人常用gradle插件与android studio插件
- Android Studio多渠道打包和代码混淆教程
- z-index和transform,你真的了解吗?
- android开源框架android-async-http使用
- javaScript的再次学习
- UE4的旋转笔记
- web.xml配置详解
- 使用Eric构建使用Caffe应用程序