LeetCode 每日一题 1207. 独一无二的出现次数

java击败100%的哈希表方法:用数组代替哈希表

普通哈希表

使用哈希表,一遍记录,一遍去重,思路简单。

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int num : arr) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        Set<Integer> set = new HashSet<>();
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int value = entry.getValue();
            if(set.contains(value)) return false;
            else set.add(value);
        }
        return true;
    }
}

时间复杂度

遍历一遍数组一遍值域 O ( n + k ) O(n + k) O(n+k)

空间复杂度

同理, O ( n + k ) O(n + k) O(n+k)

加速哈希表

本题数据长度只有不超过1000,并且数据范围为 [ − 1000 , 1000 ] [-1000, 1000] [1000,1000],因此可以使用数组来代替哈希表记录和去重,访问速度大大加快。

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        int[] map = new int[2001];
        for(int num : arr) map[num + 1000]++;
        boolean[] set = new boolean[1001];
        for(int i = 0; i < map.length; i++) {
            if(map[i] == 0) continue;
            if(set[map[i]]) return false;
            else set[map[i]] = true;
        }
        return true;
    }
}

image.png

image.png

可以看出速度有了“很大”的提升!

时间复杂度

遍历一遍数组一遍值域 O ( n + k ) O(n + k) O(n+k)

空间复杂度

同理, O ( n + k ) O(n + k) O(n+k)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值