Trapping Rain Water
来源:互联网 发布:少年包青天3知乎 编辑:程序博客网 时间:2024/05/22 01:43
为什么我的思路总是和别人的不一样呢……
具体想法是,设想这些墙都是排成一队的人,那么总有一个最高的墙,在这个墙左边,每个墙能存的雨水就和他向右看能看到的墙的个数有关,直到某一个比他还高的墙将他视线挡住为止。那么,在这两个比较高的墙之间,就是可以存雨水的部分。最高墙的右侧类似,只不过是需要向左看。
因此,首先找到最高的墙是哪个,然后左右分开处理即可。
class Solution {public: int trap(int A[], int n) { int index_max = -1; int max = INT_MIN; for (int i = 0; i < n; ++i) if (A[i] > max) { index_max = i; max = A[i]; } int res = 0; int i = 1; int tmp_max = A[0]; while (i < index_max) { if (A[i] < tmp_max) { res += tmp_max - A[i]; ++i; } else { tmp_max = A[i]; ++i; } } i = n - 2; tmp_max = A[n - 1]; while (i > index_max) { if (A[i] < tmp_max) { res += tmp_max - A[i]; --i; } else { tmp_max = A[i]; --i; } } return res; }};
http://oj.leetcode.com/problems/trapping-rain-water/
0 0
- LeetCode: Trapping Rain Water
- LeetCode : Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- [Leetcode] Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- [LeetCode]Trapping Rain Water
- Trapping Rain Water
- Trapping Rain Water
- LeetCode-Trapping Rain Water
- Trapping Rain Water
- [leetcode] Trapping Rain Water
- Trapping Rain Water
- [LeetCode] Trapping rain water
- Leetcode: Trapping Rain Water
- 38 - Trapping Rain Water
- EXTjs获取元素
- Lamobo M1
- Linux内存文件系统——tmpfs(/dev/shm)
- FORM的并发性问题与并发锁
- 浅谈BSTR,_bstr_r,VARIANT,_variant_t. VARIANT类型如何与CString互转
- Trapping Rain Water
- IOS设计模式之二(门面模式,装饰器模式)
- jquery获取复选框的值
- ln命令
- 进程的创建 —— do_fork()函数详解
- Android GestureDetector手势识别类
- 释放Win8.1 WinSxS冗余更新
- IOS设计模式之三(适配器模式,观察者模式)
- Touch事件原理