https://www.lintcode.com/problem/pour-water/description
public class Solution {
/**
* @param heights: the height of the terrain
* @param V: the units of water
* @param K: the index
* @return: how much water is at each index
*/
public int[] pourWater(int[] heights, int V, int K) {
// Write your code here
for (int i = 0; i < V; i++) {
int minLeft = findLeftMin(K, heights);
if (minLeft != K) {
heights[minLeft]++;
} else {
int rightMin = findRightMin(K, heights);
if (rightMin != K) {
heights[rightMin]++;
} else {
heights[K]++;
}
}
}
return heights;
}
private int findRightMin(int k, int[] heights) {
int index = k;
for (int i = k + 1; i < heights.length; i++) {
if (heights[i] < heights[index]) {
index = i;
} else if (heights[i] > heights[index]) {
break;
}
}
return index;
}
private int findLeftMin(int k, int[] heights) {
int index = k;
for (int i = k - 1; i >= 0; i--) {
if (heights[i] < heights[index]) {
index = i;
} else if (heights[i] > heights[index]) {
break;
}
}
return index;
}
}
网友评论