LeetCode Container With Most Water
2015-12-30 23:59
507 查看
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.
题意:给出一个非负数组,找出其中两个构成的最大容积
思路:从两边开始逐渐缩小区间。如果左边的小于右边的,更新最大容积,并且区间左值右移,否则区间右值左移
与Trapping Rain Water相似
代码如下:
class Solution
{
public int maxArea(int[] height)
{
int left = 0, right = height.length - 1;
int ans = 0;
while (left < right)
{
int tmp = 0;
if (height[left] < height[right])
{
tmp = height[left] * (right - left);
left++;
}
else
{
tmp = height[right] * (right - left);
right--;
}
ans = Math.max(ans, tmp);
}
return ans;
}
}
..., 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.
题意:给出一个非负数组,找出其中两个构成的最大容积
思路:从两边开始逐渐缩小区间。如果左边的小于右边的,更新最大容积,并且区间左值右移,否则区间右值左移
与Trapping Rain Water相似
代码如下:
class Solution
{
public int maxArea(int[] height)
{
int left = 0, right = height.length - 1;
int ans = 0;
while (left < right)
{
int tmp = 0;
if (height[left] < height[right])
{
tmp = height[left] * (right - left);
left++;
}
else
{
tmp = height[right] * (right - left);
right--;
}
ans = Math.max(ans, tmp);
}
return ans;
}
}
相关文章推荐
- LeetCode: 008-Contains Duplicate
- UVa 10976 Fractions Again?!(分数拆分)
- ArcGIS Server:Service failed to start
- 2014 Multi-University Training Contest 1 - J Rating
- Brainiac Designer
- 书-Programming Game AI by Example
- glib g_main_loop理解
- AS开发AIDL程序(2)
- 使用AS开发AIDL程序(1)
- opencv_traincascade.exe用到的参数及解释
- Factorial Trailing Zeroes 阶乘的后边有几个0
- ld: library not found for -lPods clang: error: linker command failed with exit code 1 (use -v to see
- wait_event_interruptible 使用方法
- web.xml中<security-constraint>和四种认证类型
- Error Domain=NSURLErrorDomain Code=-999错误
- AIDL:进程间通信
- 采用airbnb的airpal和facebook的presto搭建数据平台所遇到的时区,权限问题
- 070 - Climbing Stairs
- POJ-2010 Moo University - Financial Aid
- 自定义View时,用到Paint Canvas的一些温故,只有想不到没有做不到(实例 1,画一个简单的Activity并且实现他能实现的)