Leetcode1207独一无二的出现次数

在这里插入图片描述
java采用HashMap+Set实现,HashMap用于记录每个数出现的次数,之后存到Set中进行判断

class Solution {
    
    
    public boolean uniqueOccurrences(int[] arr) {
    
    
        Map<Integer,Integer> count = new HashMap<Integer,Integer>();
        for(Integer i : arr){
    
    
            if(count.containsKey(i)){
    
    
                count.put(i,count.get(i)+1);
            }else{
    
    
                count.put(i,1);
            }
        }
        int size = count.size();
        Set<Integer> set = new HashSet<Integer>();
        //map中对于值的遍历
        //对于key是Integer key :map.keys
        for(Integer value:count.values()){
    
    
            set.add(value);
        }
        if(set.size() == size){
    
    
            return true;
        }
        return false;
    }
}

d.get(i,0) 如果集合中没有值默认赋为0

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        d = {
    
    }
        for i in arr:
            d[i] = d.get(i,0) + 1
        s = [d[i] for i in d]
        return len(s)==len(set(s))

猜你喜欢

转载自blog.csdn.net/weixin_43812609/article/details/109341150