forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
217.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>
struct HashNode {
int data;
struct HashNode *next;
};
static inline int hash(int num, int size) {
int index = num % size;
return (index > 0) ? (index) : (-index);
}
bool containsDuplicate(int* nums, int numsSize) {
if (numsSize < 2) return false;
bool duplicated = false;
int hash_size = numsSize / 2 + 1; /* proper size can be faster */
struct HashNode **hash_table
= (struct HashNode **)calloc(hash_size, sizeof(struct HashNode *));
int i;
for (i = 0; i < numsSize; i++) {
int index = hash(nums[i], hash_size);
struct HashNode **p = hash_table + index;
while (*p) {
if ((*p)->data == nums[i]) {
duplicated = true;
goto OUT;
}
p = &((*p)->next);
}
struct HashNode *new_node
= (struct HashNode *)malloc(sizeof(struct HashNode));
new_node->data = nums[i];
new_node->next = NULL;
*p = new_node;
}
OUT:
for (i = 0; i < hash_size; i++) {
struct HashNode *t = hash_table[i];
struct HashNode *x = NULL;
while (t) {
x = t->next;
free(t);
t = x;
}
}
free(hash_table);
return duplicated;
}
int main() {
int nums[] = { 1, 3, 5, 7, 9, 7 };
/* should be 1 */
printf("%d\n", containsDuplicate(nums, sizeof(nums) / sizeof(nums[0])));
return 0;
}