645.错误的集合。哈希表0ms

本文介绍了一种算法,通过计数哈希表中元素出现次数,找出数组中出现两次的重复元素和缺失的唯一元素。Solution类中的findErrorNums方法展示了如何实现这一功能,适用于查找并返回数组中的重复与缺失值。
// 哈希中出现2次的是重复元素,未出现的则是缺失元素,返回这两个即可
class Solution {
    public int[] findErrorNums(int[] nums) {
        // 哈希中出现2次的是重复元素,未出现的则是缺失元素,返回这两个即可
        int len = nums.length;
        int[] count = new int[len + 1];
        for(int num : nums) count[num]++;
        int[] res = new int[2];
        for(int i = 1; i <= len; i++){
            if(count[i] == 0) res[1] = i;
            if(count[i] == 2) res[0] = i;
        }
        return res;
    }
}
题目 7-369 用户 LWY 提交时间 2025/08/18 13:10:18 编译器 C (gcc) 内存 512 / 65536 KB 用时 1 / 1000 ms 状态 答案错误 分数 0 / 35 评测时间 2025/08/18 13:10:19 评测详情 测试点 提示 内存(KB) 用时(ms) 结果 得分 0 304 1 答案错误 0 / 6 1 304 1 答案错误 0 / 6 2 512 1 答案错误 0 / 2 3 304 1 答案错误 0 / 2 4 304 1 答案错误 0 / 4 5 344 1 答案错误 0 / 4 6 304 1 答案错误 0 / 2 7 340 1 答案错误 0 / 2 8 304 1 答案错误 0 / 3 9 304 1 答案错误 0 / 2 10 344 1 答案错误 0 / 2 提交代码 复制内容 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #define MOD 1000000007 #define MAXN 2005 #define MAXS 50005 #define HASH_SIZE 100007 // 定义 Node 结构体 typedef struct Node { char *str; struct Node *next; } Node; // 替代 strdup char* my_strdup(const char* s) { char* copy = (char*)malloc(strlen(s) + 1); if (copy) strcpy(copy, s); return copy; } // 哈希函数(BKDR Hash) unsigned int BKDRHash(char *str) { unsigned int seed = 131; unsigned int hash = 0; while (*str) { hash = hash * seed + (*str++); } return hash % HASH_SIZE; } // 插入字符串到哈希表中(去重) int insertHash(char *str, Node *hashTable[]) { 编译器输出 a.c: In function ‘main’: a.c:54:5: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result] 54 | scanf("%d", &n); | ^~~~~~~~~~~~~~~ a.c:62:9: warning: ignoring return value of ‘scanf’ declared with attribute ‘warn_unused_result’ [-Wunused-result] 62 | scanf("%s", buffer); | ^~~~~~~~~~~~~~~~~~~
08-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值