- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path217.c
65 lines (53 loc) · 1.46 KB
/
217.c
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
structHashNode {
intdata;
structHashNode*next;
};
staticinlineinthash(intnum, intsize) {
intindex=num % size;
return (index>0) ? (index) : (-index);
}
boolcontainsDuplicate(int*nums, intnumsSize) {
if (numsSize<2) return false;
boolduplicated= false;
inthash_size=numsSize / 2+1; /* proper size can be faster */
structHashNode**hash_table
= (structHashNode**)calloc(hash_size, sizeof(structHashNode*));
inti;
for (i=0; i<numsSize; i++) {
intindex=hash(nums[i], hash_size);
structHashNode**p=hash_table+index;
while (*p) {
if ((*p)->data==nums[i]) {
duplicated= true;
goto OUT;
}
p=&((*p)->next);
}
structHashNode*new_node
= (structHashNode*)malloc(sizeof(structHashNode));
new_node->data=nums[i];
new_node->next=NULL;
*p=new_node;
}
OUT:
for (i=0; i<hash_size; i++) {
structHashNode*t=hash_table[i];
structHashNode*x=NULL;
while (t) {
x=t->next;
free(t);
t=x;
}
}
free(hash_table);
returnduplicated;
}
intmain() {
intnums[] = { 1, 3, 5, 7, 9, 7 };
/* should be 1 */
printf("%d\n", containsDuplicate(nums, sizeof(nums) / sizeof(nums[0])));
return0;
}