LeetCode 42. Trapping Rain Water
来源:互联网 发布:知乎 最刺激的事情 编辑:程序博客网 时间:2024/04/28 22:56
用了6ms,只击败了6%的提交者,表示好坑,之后会进一步改良与完善注释,先就这样:
import java.util.LinkedList;public class Solution { public static class Pair{ public int height; public int index; public Pair(int height, int index) { super(); this.height = height; this.index = index; } } public int trap(int[] height) { if(height==null||height.length<3) return 0; LinkedList<Pair> list = new LinkedList<>(); int lowest = height[0]; list.add(new Pair(lowest,0)); int sum = 0; for (int i = 1; i < height.length; i++) { if(lowest < height[i]){ if(list.size()==1){ list.pop();//上升阶段 list.push(new Pair(height[i],i)); lowest = height[i]; }else{ while(true){ if(list.size()==1){ list.clear(); list.push(new Pair(height[i],i)); break; } Pair behind = list.pop(); if(behind.height>height[i]){ list.push(behind); break; } Pair front = list.pop(); if(front.height>=height[i]){ sum+=(i-behind.index)*(height[i]-behind.height); list.push(front); list.push(new Pair(height[i],behind.index)); break; }else{ sum+=(i-behind.index)*(front.height-behind.height); list.push(front); } } lowest = list.peek().height; } } if(lowest > height[i]){//下降阶段 list.push(new Pair(height[i],i)); lowest = height[i]; } } return sum ; }}
看别人做的,基本思路就是记录每个坑需要的注水量,
先把每个‘坑’左侧最高和右侧最高计算出来
需要注水的话 min(左侧最高,右侧最高)-本身高度就是需要的注水量
public class Solution3 { public int trap(int[] height) { if(height.length<3){ return 0; } int[] maxleft = new int[height.length]; int[] maxRight = new int[height.length]; maxleft[0] = height[0]; for(int i=1;i<height.length;i++){ maxleft[i] = max(maxleft[i-1], height[i]); } maxRight[height.length-1] = height[height.length-1]; for(int i=height.length-2;i>0;i--){ maxRight[i] = max(maxRight[i+1], height[i]); } int sum = 0; for (int i = 0; i < height.length; i++) { sum+=max(0, min(maxleft[i], maxRight[i])-height[i]); } return sum; } public int max(int a,int b){ return a>b?a:b; } public int min(int a,int b){ return a<b?a:b; }}
0 0
- [LeetCode]42.Trapping Rain Water
- LeetCode --- 42. Trapping Rain Water
- LeetCode 42.Trapping Rain Water
- [Leetcode] 42. Trapping Rain Water
- [leetcode] 42.Trapping Rain Water
- 【leetcode】42. Trapping Rain Water
- ***LeetCode 42. Trapping Rain Water
- Leetcode 42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- [LeetCode]42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- leetcode.42. Trapping Rain Water
- [leetcode] 42. Trapping Rain Water
- LeetCode-42.Trapping Rain Water
- LeetCode 42. Trapping Rain Water
- bootstrap样式大全
- 第一讲 计算机工作原理
- pandas教程_记录百度知道链接
- 机器人软件平台开发
- 剑指offer(35):丑数
- LeetCode 42. Trapping Rain Water
- 关于升级 win10 后打不开网页的小问题!
- 大学值不值得上?
- 《大学ACM的总结 》(转载)
- 浅谈session和cookie
- Nova 组件详解 - 每天5分钟玩转 OpenStack(26)
- Hello Android Hello Java
- PullToRefresh的简单使用
- 遍历文件夹下某种类型文件名(C++)