|
| 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