题目描述
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
示例 1:
输入: [1,2,3,1] 输出: true 示例 2:
输入: [1,2,3,4] 输出: false 示例 3:
输入: [1,1,1,3,3,4,3,2,4,2] 输出: true
来源:力扣(LeetCode) 链接: 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路分析
通过hash函数判断元素是否相同
AC 代码
typedef struct node {
int val;
struct node *next;
} node;
#define LEN 256
void free_node(node **n) {
for (int i = 0; i < LEN; ++i) {
node *next = n[i];
while (next != NULL) {
node *temp = next;
next = next->next;
free(temp);
}
}
}
char containsDuplicate(int* nums, int numsSize){
node *(n[LEN]);
for (int i = 0; i < LEN; ++i) {
n[i] = NULL;
}
for (int i = 0; i < numsSize; ++i) {
int x = (nums[i] & 0x7fffffff) % LEN;
if (n[x] != NULL) {
node *next = n[x];
while (next != NULL && next->val != nums[i]) {
next = next->next;
}
if (next != NULL) {
free_node(n);
return 1;
}
node *temp = calloc(1, sizeof(node));
temp->val = nums[i];
temp->next = n[x];
n[x] = temp;
continue;
}
node *temp = calloc(1, sizeof(node));
temp->val = nums[i];
n[x] = temp;
}
free_node(n);
return 0;
}
总结
简易哈希表,后续可以优化哈希算法进行空间和时间的优化
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情