135. Candy

 follow up:如何不使用extra space解決這道題

https://leetcode.com/problems/candy/solution/

Approach 4: Single Pass Approach with Constant Space
Algorithm



https://leetcode.com/problems/candy/discuss/42770/One-pass-constant-space-Java-solution

利用BST中序遍歷是單調遞增的性質。維護一個curVal,在中序遍歷的時候,若是root.val == curVal,更新curFreq。由於BST保證了你只會在連續幾個node的時候碰到相同的val.不可能你剛開始遍歷了幾個4,而後遍歷了幾個5,而後又遍歷到4.


 給你一個BST, 可是這個BST是有duplicate的,問你在這棵BST中出現頻率最高的那個數字是什麼,以及頻率是多少。 follow up是, 不用extra space

請問樓主,生成迷宮能夠用 https://en.wikipedia.org/wiki/Maze_generation_algorithm 上說的 Recursive backtracker 寫嗎?感受這個方法還挺直接的

我以爲這個挺對的!稍微變種一下這個recursive backtracker的思想就好。wiki上的例子wall是不佔用一個格子的,因此wiki上的goal是要遍歷全部的cell。但咱們這裏wall要佔用格子,那麼咱們能夠把全部i, j 爲偶數的(i, j) 格子當作cell,其餘的格子當作是wall,目標就是把全部的cell格子遍歷一遍。這樣知足了題目中不能產生2*4thick wall 的條件,由於wall最厚也只能是1.

]]
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.




https://www.youtube.com/watch?v=-XWLumbr4UU


https://leetcode.com/problems/candy/discuss/42774/Very-Simple-Java-Solution-with-detail-explanation



class Solution {
    public int candy(int[] ratings) {
        
        // fill in the array with 1 first , and then iterate from left to right 
        // if next one is bigger , then next one is cur one + 1 , 
        // next one is not bigger, then next one stays the same 
        
        // iterate from right to left, if next one is bigger , next one is max(cur + 1, next one)
        // if next one is not bigger, next one stays the same 
        
        // then iterate thru the whole array and get the result 
        // or we can update the result the second traversal from right to left
        // 1 0 2 
        // 1 1 2 
        int[] array = new int[ratings.length];
        Arrays.fill(array, 1);
        for(int i = 0; i < array.length - 1; i++){  // i < 3 - 1 = 2 , i < 2, i = 0, 1 
            if(ratings[i + 1] > ratings[i]){
                array[i + 1] = array[i] + 1;
                // i + 1 = 1, 2
            }
        }
        // from right to left 
        int res = 0;
        for(int i = array.length - 1; i > 0; i--){
            if(ratings[i - 1] > ratings[i]){
                array[i - 1] = Math.max(array[i - 1], array[i] + 1);
            }
        }
        for(int i = 0; i < array.length; i++){
            res += array[i];
        }
        return res;
    }
}
相關文章
相關標籤/搜索