LeetCode -- Container With Most Water
来源:互联网 发布:数控编程教学视频 编辑:程序博客网 时间:2024/05/31 04:03
题目描述:
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.
已知一个height数组,代表从0到n的纵坐标,对于height[i]和height[j]来说,它们构成的最大水容量为i和j的距离 * Min(height[i], height[j])。问,求出height数组中哪两点间的水容量最大?
思路:
算是一个two pointer的经典问题,左右两边开始找,left=0,right = n-1:
1. 如果左边高度低,则left++;如果右边高度低,则r--;如果相等,则left++并且right--;
2. 每次计算左右两点的水容量,并更新max值即可
实现代码:
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.
已知一个height数组,代表从0到n的纵坐标,对于height[i]和height[j]来说,它们构成的最大水容量为i和j的距离 * Min(height[i], height[j])。问,求出height数组中哪两点间的水容量最大?
思路:
算是一个two pointer的经典问题,左右两边开始找,left=0,right = n-1:
1. 如果左边高度低,则left++;如果右边高度低,则r--;如果相等,则left++并且right--;
2. 每次计算左右两点的水容量,并更新max值即可
实现代码:
public class Solution { public int MaxArea(int[] height) { var l = 0; var r = height.Length - 1; var max = 0; while(l < r){ var current = Math.Min(height[l], height[r]) * (r - l); max = Math.Max(max , current); if(height[l] < height[r]){ l++; } else if(height[l] > height[r]){ r--; } else{ l++; r--; } } return max; }}
1 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
- Maven初步学习
- 苹果vs谷歌:与微软的战争教会了苹果什么
- JAVA多线程和并发基础面试问答(转载)
- 2015 Changchun F
- spring数据源配置
- LeetCode -- Container With Most Water
- ARM中关于绝对寻址相对寻址LDR,ADR的理解
- LeetCode -- Remove Invalid Parentheses
- Nexus私服使Maven更加强大
- 3D数学基础:图形与游戏开发_读书笔记01
- struts2读常量顺序
- Node Security
- Android中Canvas绘图基础详解(附源码下载)
- LeetCode -- Set Matrix Zeroes