26 Unique Number of Occurrences

关注 每天一道编程题 专栏,一起学习进步。

题目

Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Constraints:

1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000

分析

题意:不同的数字拥有不同的个数,则为真,反之为假;
意思就是对数组中的数字进行计数,要保证每个数的个数都是不一样的。

算法:
拿到arr当前数i
将i放入一个Map中,key为arr[i],value为i出现的次数
由于Map的key具有唯一性,因此最终map的size就是对i去重之后的个数,如[1,1,2,3]最终映射到Map中只有[1,2,3]
然后将Map的value转为set,set也会去重。
如果set.size==Map.size,则为true

举例:
arr=[1,1,2,3,3,3]
Map={1:2,2:1,3:3}.size=3
Set={2,1,3}.size=3
为true

arr=[1,1,2,2]
Map={1:2,2:2}.size=2
Set={2}.size=1
为false

解答

class Solution {
      public boolean uniqueOccurrences(int[] arr) {
      Map<Integer, Integer> count = new HashMap<>();
      for (int a : arr)
          //注意,getOrDefault也会扫描当前正准备插进去的key,
          // 因此当当前getOrDefault(key,)的key等于put(key,)的key时,1+getOrDefault(kye,0)起到了对key计数的功能
          count.put(a, 1 + count.getOrDefault(a, 0));
      //由于map的key具有唯一性,因此count.size()为对key去重之后的size
      //set.size()是对value去重之后的size
      return count.size() == new HashSet<>(count.values()).size();
  }
}

解法的亮点在于:

map.put(key,1+map.getOrDefault(key,0))

实现了对值的去重且记录值的实际个数

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值