11. Container With Most Water(求能装最多水的容器)
来源:互联网 发布:js改变css display 编辑:程序博客网 时间:2024/05/20 07:33
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.
题目大意:给定一个长度为n的数组a[n],在二维空间形成n个点(x=i,y=a[i]),找出两个点,使得这两个点到x轴的垂线与x轴构成一个容器,容器的容积最大。容器不能倾斜,而且n>=2。
解题思路:
对于n个点,要求得最大的容积,可以分两种情况:
1. 宽度为n,高度为a[0]和a[n-1]中较小的值;
2. 舍弃掉(i,a[i])这个点,其中i = a[0]和a[n-1]中较小的值的下标,然后在剩下的n-1个点中找得两个点,构成容积最大的容器。
直到宽度为1的时候,直接去高度为a[i]。
递归代码:(leetcode测试用例太大,报了StackOverFlow)
class Solution { public int findMax(int left, int right, int[] height) {if (right - left == 1) {return Math.min(height[left], height[right]);}int bigger;if (height[left] > height[right]) {bigger = findMax(left, right - 1, height);} else {bigger = findMax(left + 1, right, height);}return Math.max(Math.min(height[left], height[right]) * (right - left), bigger);}public int maxArea(int[] height) {return findMax(0, height.length - 1, height);}}
class Solution { public int maxArea(int[] height) {int len = height.length;int[] area = new int[len];int left = 0, right = len - 1;while (right > left) {area[right - left - 1] = (right - left) * Math.min(height[left], height[right]);if (height[left] > height[right]) {right--;} else {left++;}}int max = 0;for (int i = 0; i < len; i++) {if (area[i] > max) {max = area[i];}}return max;}}
阅读全文
0 0
- 11. Container With Most Water(求能装最多水的容器)
- Leetcode刷题记——11. Container With Most Water(装最多水的容器)
- Container With Most Water (容器中盛最多的水)
- Container With Most Water(能装最多水的容器)
- 含水最多的容器(Container With Most Water)
- Container With Most Water --装最多水的容器(重)
- LeetCode OJ 之 Container With Most Water(能装最多水的容器)
- 383.Container With Most Water-装最多水的容器(中等题)
- 383.Container With Most Water-装最多水的容器(中等题)
- 6.container-with-most-water(装最多水的容器)
- LeetCode | Container with most water(装最多的水)
- LeetCode 11. Container With Most Water(容器装水)
- Container With Most Water 求容器里能放最多的水 @LeetCode
- LeetCode 11. Container With Most Water(盛最多的水)
- Container With Most Water 盛最多的水
- Container With Most Water 装最多的水
- Container With Most Water容器盛水
- Container With Most Water(最大容器)
- Linux命令分析: locate
- SQL入门经典(第5版)第六章 管理数据库事务
- react中使用Link在不同路由之间进行参数传值
- MongoDB可视化工具
- SQL SERVER中查询当天、当月、当年数据的SQL语句
- 11. Container With Most Water(求能装最多水的容器)
- Python3 与 Python2 的不同
- 基于MVC开发模式的javaWeb项目开发流程
- 面试遇到的一个递归题目
- 五、模板字面量
- 织梦CMS(Dedecms)提示信息页的修改方法
- Win32多线程编程
- Spring相关题目
- codeblocks下载安装及问题解决