【哈希容器】1207. 独一无二的出现次数

1207. 独一无二的出现次数

解题思路

  • 首先使用hashmap 存储每一个数组元素的出现次数
  • 然后创建一个hashset
  • 增强for循环遍历hashmap 查看hashSet中是否存在该value
class Solution {
    
    
    public boolean uniqueOccurrences(int[] arr) {
    
    
       // 创建一个hashmap

    //    Map<Integer,String> map = new HashMap<>();
        Map<Integer,Integer> map = new HashMap<>();
        // List<Integer> list = new ArrayList<>();// 存储所有的hash value
        int[] nums = new int[2001];

        for(int i = 0; i < arr.length; i++){
    
    
            map.put(arr[i],0);// 全部初始化为0
        }

        for(int k = 0; k < arr.length; k++){
    
    
            int temp = map.get(arr[k]) + 1;
            map.replace(arr[k],temp);// 替换元素
        }
        // 使用hashset 来检查出现次数是不是唯一
        Set<Integer> set = new HashSet<>();

        for(int count: map.values()){
    
    
            // 遍历每一个value

            if(set.contains(count)){
    
    
                return false;//说明出现过 
            }
            else{
    
    
                set.add(count);// 没有出现过
            }
        }
        return true;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/131782445