You are given an elevation map represents as an integer array heights
where heights[i]
representing the height of the terrain at index i
. The width at each index is 1
. You are also given two integers volume
and k
. volume
units of water will fall at index k
.
Water first drops at the 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 to its 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 is 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 one grid block, and each unit of water has to be in exactly one block.
Example 1:
Input: heights = [2,1,1,2,1,2,2], volume = 4, k = 3 Output: [2,2,2,3,2,2,2] Explanation: The first drop of water lands at index k = 3. When moving left or right, the water can only move to the same level or a lower level. (By level, we mean the total height of the terrain plus any water in that column.) Since moving left will eventually make it fall, it moves left. (A droplet "made to fall" means go to a lower height than it was at previously.) Since moving left will not make it fall, it stays in place.
思路:模拟水滴走的过程,这里看的花花的视频,drop函数写的太巧妙了,往左走和往右走用一个函数表示,就是找到最低的位置,然后+1;best != k,表明找到了就直接break,只用找一个就行了;
class Solution {
public int[] pourWater(int[] heights, int volume, int k) {
while(volume > 0) {
drop(heights, k);
volume--;
}
return heights;
}
private void drop(int[] heights, int k) {
int best = k;
for(int d = -1; d <= 1; d += 2) {
int i = k + d;
while(0 <= i && i < heights.length && heights[i] <= heights[i - d]) {
if(heights[i] < heights[best]) {
best = i;
}
i += d;
}
if(best != k) {
break;
}
}
heights[best]++;
}
}