*LeetCode-Candy

24 篇文章 0 订阅
15 篇文章 0 订阅

一开始的思路是先把这个ratings array sort 然后从小的rating开始fix 之后fix更大的 小的就不会受影响 

但是排序的话就需要储存位置和rating值 需要用map 废了空间 还sort费时间 超时了

但是也练习了一下如何sort map basing on value

public class Solution {
    public int candy(int[] ratings) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for ( int i = 0; i < ratings.length; i ++ ){
            map.put ( i, ratings[ i ] );
        }
        List<Map.Entry<Integer, Integer>> list = new LinkedList<Map.Entry<Integer, Integer>>( map.entrySet());
        Collections.sort ( list, new Comparator<Map.Entry<Integer, Integer>> (){
            public int compare ( Map.Entry<Integer, Integer> en1, Map.Entry<Integer, Integer> en2 ){
                return en1.getValue() - en2.getValue();
            }
        });
        int [ ] num = new int [ ratings.length ];
        Arrays.fill ( num, 1 );
        for ( int i = 0; i < list.size(); i ++ ){
            Map.Entry<Integer, Integer> en = list.get( i );
            int id = en.getKey();
            int left = (id - 1 >= 0 ? id - 1 : id);
            int right = (id + 1 < ratings.length ? id + 1  : id);
            if ( ratings [ left ] < ratings [ id ] && ratings [ right ] < ratings [ id ] ){
                num [ id ] = Math.max ( num [left], num [right] ) + 1;
            }
            else if ( ratings [ left ] < ratings [ id ] )
                num [ id ] = num [ left ] + 1;
            else if ( ratings[ right ] < ratings [ id ] )
                num [ id ] = num [ right ] + 1;
        }
        int res = 0;
        for ( int i : num )
            res += i;
        return res;
    }
}

后来发现正着扫一遍 再反着扫一遍就可以了每次只看前一个数字

public class Solution {
    public int candy(int[] ratings) {
        if ( ratings == null || ratings.length == 0 )
            return 0;
        int [] num = new int [ ratings.length ];
        Arrays.fill ( num, 1 );
        for ( int i = 1; i < ratings.length; i ++ ){
            if ( ratings [ i ] > ratings [ i - 1 ] )
                num [ i ] = num [ i - 1 ] + 1;
        }
        for ( int i = ratings.length - 2; i >= 0; i -- ){
            if ( ratings [ i ] > ratings [ i + 1 ] && num [ i ] <= num [ i + 1 ] )
                num [ i ] = num [ i + 1 ] + 1;
        }
        int res = 0;
        for ( int n : num )
            res += n;
        return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值