Skip to content

Commit 6c6a107

Browse files
committed
"Contains Duplicate II"
1 parent 2301f42 commit 6c6a107

File tree

2 files changed

+77
-1
lines changed

2 files changed

+77
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ You can build all the files using `make` (Use MinGW GCC and GNU Make on Windows)
3131
| 222 | [Count Complete Tree Nodes] | [C](src/222.c) |
3232
| 221 | [Maximal Square] | |
3333
| 220 | [Contains Duplicate III] | |
34-
| 219 | [Contains Duplicate II] | |
34+
| 219 | [Contains Duplicate II] | [C](src/219.c) |
3535
| 218 | [The Skyline Problem] | |
3636
| 217 | [Contains Duplicate] | [C](src/217.c) |
3737
| 216 | [Combination Sum III] | |

src/219.c

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <stdbool.h>
4+
5+
struct HashNode {
6+
int data;
7+
int index;
8+
struct HashNode *next;
9+
};
10+
11+
static inline int hash(int num, int size) {
12+
int index = num % size;
13+
return (index > 0) ? (index) : (-index);
14+
}
15+
16+
bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
17+
if (numsSize < 2) return false;
18+
bool duplicated = false;
19+
20+
int hash_size = numsSize / 2 + 1; /* proper size can be faster */
21+
struct HashNode **hash_table
22+
= (struct HashNode **)calloc(hash_size, sizeof(struct HashNode *));
23+
24+
int i;
25+
for (i = 0; i < numsSize; i++) {
26+
int index = hash(nums[i], hash_size);
27+
struct HashNode **p = hash_table + index;
28+
29+
while (*p) {
30+
if ((*p)->data == nums[i]) {
31+
int distance = abs((*p)->index - i);
32+
if (distance <= k) {
33+
duplicated = true;
34+
goto OUT;
35+
}
36+
else {
37+
(*p)->index = i; /* update to nearer index */
38+
}
39+
}
40+
p = &((*p)->next);
41+
}
42+
43+
struct HashNode *new_node
44+
= (struct HashNode *)malloc(sizeof(struct HashNode));
45+
new_node->data = nums[i];
46+
new_node->index = i;
47+
new_node->next = NULL;
48+
49+
*p = new_node;
50+
}
51+
52+
OUT:
53+
for (i = 0; i < hash_size; i++) {
54+
struct HashNode *t = hash_table[i];
55+
struct HashNode *x = NULL;
56+
while (t) {
57+
x = t->next;
58+
free(t);
59+
t = x;
60+
}
61+
}
62+
free(hash_table);
63+
64+
return duplicated;
65+
}
66+
67+
int main() {
68+
int nums[] = { 1, 3, 5, 7, 9, 2, 7, 4, 7 };
69+
/* should be true */
70+
printf("%d\n", containsNearbyDuplicate(nums, sizeof(nums) / sizeof(nums[0]), 2));
71+
72+
/* should be false */
73+
printf("%d\n", containsNearbyDuplicate(nums, sizeof(nums) / sizeof(nums[0]), 1));
74+
75+
return 0;
76+
}

0 commit comments

Comments
 (0)