LeetCode 11. Container With Most Water(容器装水)
2016-05-19 05:24
483 查看
原题网址:https://leetcode.com/problems/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.
方法一:构造一个递增容器序列,当遇到高度降低时,检查左边所有可能的容器。
方法二:从左右两边往中间扫描,当其中一边较矮的时候,及时计算该侧所能装的水,然后该侧内移。
方法一和二的思路:
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.
方法一:构造一个递增容器序列,当遇到高度降低时,检查左边所有可能的容器。
public class Solution { public int maxArea(int[] height) { List<Integer> list = new ArrayList<>(); int max = 0; int area = 0; for(int i=0; i<height.length; i++) { if (list.isEmpty() || height[list.get(list.size()-1)] < height[i]) { list.add(i); } else { for(int j=0; j<list.size(); j++) { area = (i-list.get(j)) * Math.min(height[list.get(j)], height[i]); if (area > max) max = area; if (height[list.get(j)] > height[i]) break; } } } for(int j=0; j<list.size()-1; j++) { area = (list.get(list.size()-1) - list.get(j)) * height[list.get(j)]; if (area > max) max = area; } return max; } }
方法二:从左右两边往中间扫描,当其中一边较矮的时候,及时计算该侧所能装的水,然后该侧内移。
public class Solution { public int maxArea(int[] height) { int max = 0; int left = 0, right = height.length-1; while (left < right) { if (height[left] < height[right]) { int area = height[left] * (right-left); if (area > max) max = area; left ++; } else if (height[left] > height[right]) { int area = height[right] * (right-left); if (area > max) max = area; right --; } else { int area = height[left] * (right-left); if (area > max) max = area; left ++; right --; } } return max; } }
方法一和二的思路:
相关文章推荐
- RAD Studio 10 安装失败 提示错误 License status check failure解决办法
- leetcode 11. Container With Most Water
- 使用 SDL 过程中遇到的两个问题: 找不到main函数 和 链接错误
- ansible 报错 FAILED | rc=0 >> MODULE FAILURE 解决方法
- codeforces 675E E. Trains and Statistic(线段树+dp)
- 问题解决了,可是为什么呢?could not find the main class.program will exitmain
- hdu 2476 String Painter
- UVa-442-Matrix Chain Multiplication
- ORA-01122: database file 4 failed verification check
- HDU 1848 —— Fibonacci again and again 【博弈 sg函数】
- HDU 2746 ——String painter
- uva 253 Cube painting
- LightOj--1071--Baker Vai(拆点最大费用流)
- HDU 1023 Train Problem II (卡特兰数)未解决未解决未解决未解决
- WINCE MFC 自绘控件的WM_PAINT与WM_ERASEBKGND、WM_TIMER 问题总结
- 336(see). Palindrome Pairs 5.(see)
- 人工智能:一种现代方法 第四版 翻译序言
- codeforces Trains and Statistic DP
- hdu 2473 Junk-Mail Filter【并查集好题、建立虚拟节点】
- HDU 3487-Play with Chain-splay