美文网首页
Pour Water

Pour Water

作者: Frank_Kivi | 来源:发表于2018-06-27 10:29 被阅读1次

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:Pour Water

          本文链接:https://www.haomeiwen.com/subject/jaqbyftx.html