`
blue2048
  • 浏览: 182624 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]candy-java

阅读更多

两次遍历,第一遍将大于等于序列的糖果分好,第二遍反向遍历,将小于序列的糖果分好

需要注意两点

1. 等于的情况,后一个孩子的糖果为1

2. 反向遍历的时候,到已经分了糖果的边界孩子时,需要判断,反向自增的糖果和此孩子之前分的糖果哪个大,取大值

 

public class Solution {
   public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0){
            return 0;
        }
        int count = 0;
        Integer[] counter = new Integer[ratings.length];
        counter[0]=1;
        for(int i=1; i<ratings.length; i++){
            Integer pre =ratings[i-1];
            int num = ratings[i];
            if(num>pre){
                if(counter[i-1] == null){
                    counter[i]=2;
                }else {
                    counter[i]=counter[i-1]+1;
                }
            }else if(num == pre){
                counter[i] = 1;
            }
        }
        Integer firstNullIndex = null;
        for(int i=ratings.length-1; i>=0; i--){
            if(counter[i] == null && firstNullIndex==null){
                counter[i]=1;
                firstNullIndex = i;
            }else if(counter[i]==null && firstNullIndex!=null){
                counter[i]=counter[i+1]+1;
            }else if(counter[i] != null && firstNullIndex!=null){
                firstNullIndex = null;
                counter[i]=((counter[i+1]+1)>counter[i])?counter[i+1]+1:counter[i];
            }
        }
     
        for(Integer c : counter){
            if(c != null){
                count += c;
            }
        }
        return count;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics