755 Pour Water
关键词
Arrays
原题
We are given an elevation map, heights[i]
representing the height of the terrain at that index. The width at each index is 1. After V
units of water fall at index K
, how much water is at each index?
Water first drops at index K
and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules:
- If the droplet would eventually fall by moving left, then move left.
- Otherwise, if the droplet would eventually fall by moving right, then move right.
- Otherwise, rise at it’s current position.
Here, “eventually fall” means that the droplet will eventually be at a lower level if it moves in that direction. Also, “level” means the height of the terrain plus any water in that column.
We can assume there’s infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than 1 grid block - each unit of water has to be in exactly one block.
分析
- 水滴先向左滚,有低则下坠填补。当水滴滑到边缘,会有回滚操作。注意往左–,往右++。
方法
- 往左遍历有没有低谷,没有则遍历右边。
class Solution {
public:
vector<int> pourWater(vector<int>& heights, int V, int K) {
for (int i = 0; i < V; ++i) {
int l = K, r = K, n = heights.size();
while (l > 0 && heights[l] >= heights[l - 1]) --l;
while (l < K && heights[l] == heights[l + 1]) ++l;
while (r < n - 1 && heights[r] >= heights[r + 1]) ++r;
while (r > K && heights[r] == heights[r - 1]) --r;
(heights[l] < heights[K]) ? ++heights[l] : ++heights[r];
}
return heights;
}
};