11. Container With Most Water LeetCode题解
来源:互联网 发布:js变量命名的规则 编辑:程序博客网 时间:2024/06/07 12:31
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.
Subscribe to see which companies asked this question.
题意:
给定n个非负整数a1, a2, ..., an,每个代表一个坐标值(i, ai)。n条竖线的两个端点为(i, ai),(i, 0)。找到这样两条线,将他们与x轴一起组成一个容器,使得容器的容积最大。
注:容器不能倾斜,n至少为2
题解:
看到题目,想象出来的画面应该是这样的:
横轴是X轴,假设选取x=1位置和x=4位置的两根棍,则围成的容器如上图所示,蓝色部分为水,水的总体积即容积;
算法应该执行如下:
使用beg和end双指针,beg指针指向数组开头(0), end指向数组末尾(nums.size() - 1)
计算当前容积,更新最大容积大小;
然后比较beg和end中较小的一个,设法将其变大;
(因为容器容积取决于两点:1.两边棍中短的长度;2.两根棍间距;虽然间距持续变小,但是短棍的长度可能变大,总体积也会变大)
变大的方法是:
假设左边,即beg指向的棍短,则beg指针一直向右移动,直至比当前棍子长的位置停下,然后更新容积;(右边则向左边移动)
Code 【Java】
public class Solution { public int maxArea(int[] height) { int beg = 0; int end = height.length - 1; int ans = 0; while (beg < end) { int low = Math.min(height[beg], height[end]); ans = Math.max(ans, low * (end - beg)); while (height[beg] <= low && beg < end) beg++; while (height[end] <= low && beg < end) end--; } return ans; }}
Code【C++】
class Solution {public: int maxArea(vector<int>& height) { int beg = 0; int end = height.size() - 1; int ans = 0; while (beg < end) { int low = min(height[beg], height[end]); ans = max(ans, low * (end - beg)); while (height[beg] <= low && beg < end) beg++; while (height[end] <= low && beg < end) end--; } return ans; }};
- 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
- android中间件笔记
- Serlet 环境设置
- POJ 1165 The Primes 笔记
- 循环冗余检验CRC
- 判断线程池执行完,再执行下一步操作
- 11. Container With Most Water LeetCode题解
- Java MySQL 乱码问题
- ganglia的安装部署对spark集群监控
- 行为型模式之迭代器模式(Iterator)
- Dubbo框架——整体架构
- win7系统下mysql 5.7版本root用户忘记密码怎么解决
- 学习笔记: 源码 filler.hpp 简记
- Slave1 Error:JAVA_HOME is not set and could not be findz
- 在ROS中定义并使用自己的消息类型