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