Leetcode:Container With Most Water
来源:互联网 发布:淘宝店运费险怎么算的 编辑:程序博客网 时间:2024/06/01 07:16
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.
Note: You may not slant the container.
最短的板子决定容器的容量。
数组的下标代表在X轴的坐标,数组元素值则为高度。求能围成的容器的最大面积。
我们用两个变量left和right来分别指向数组的最左边和最右边,然后进行循环,循环条件为while(left<right)。此时left和right围成的面积为(right-left)*(a[left],a[right]中的较小者)。循环继续的条件:if(a[left]<a[right]),则left++;if(a[left]>a[right]),则right++。循环中记录下最大的面积max,循环结束时max的值,则为所能围城的最大面积。
实现代码如下:
public class Solution { // for any i, the maxium area will be the farthest j that has a[j] > a[i]; public int maxArea(int[] height) { if(height == null || height.length < 2) { return 0; } int max = 0; int left = 0; int right = height.length -1; while(left < right) { max = Math.max( max, (right - left) * Math.min(height[left], height[right])); if(height[left] < height[right]){ left++; } else { right--; } } return max; }}C++ Version-------------------class Solution {public: int maxArea(vector<int> &height) { int max = 0, area; int start = 0, end = height.size() - 1; while (start < end) { if (height[start] > height[end]) { area = height[end] * (end - start); end --; } else { area = height[start] * (end - start); start ++; } if (area > max) { max = area; } } return max; }};
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
- u-boot的Makefile分析(转)
- C/C++ 笔试、面试题目(转)
- 图解交换机和路由器的应用区别(转…
- [数据结构]——桶排序
- 二层交换机、三层交换机和路由器的…
- Leetcode:Container With Most Water
- 因特网网络层数据报传输机制(转)
- 路由原理介绍(转)
- C++基础知识点(转)
- C\C++基础知识,面试常见问题(转…
- C++引用与指针比较(转)
- C++引用详解(转)
- C++:区别覆盖,重载与多态(转)
- Linux下路由器的配置(转)