-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path217-containsDuplicate.c
77 lines (65 loc) · 2.03 KB
/
217-containsDuplicate.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
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Author: Angad Dogra
* GNU License
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct hashEntry {
int key ;
struct hashEntry * next ; // to chain the collisions
} ;
unsigned int hash(int key, int tableSize) {
return abs(key) % tableSize ;
}
struct hashEntry** createHashTable (int tableSize) {
struct hashEntry** table = (struct hashEntry**) malloc (tableSize * sizeof(struct hashEntry*)) ;
for (int i = 0 ; i < tableSize ; i++) {
table[i] = NULL ;
}
return table ; // returns address of the table
}
void insert (struct hashEntry** table, int key, int tableSize) {
unsigned int index = hash (key, tableSize) ;
// now check table at address index
struct hashEntry* newNode = (struct hashEntry*) malloc (sizeof (struct hashEntry)) ;
newNode -> key = key ;
newNode -> next = table[index] ;
table[index] = newNode ;
}
bool search (struct hashEntry** table, int key, int tableSize) {
unsigned int index = hash(key, tableSize) ;
struct hashEntry* node = table[index] ;
while (node != NULL) {
if (node -> key == key) {
return true ;
}
node = node -> next ; // check the linked list
}
return false ;
}
void freeHashTable (struct hashEntry** table, int tableSize) {
for (int i = 0 ; i < tableSize ; i++) {
struct hashEntry* node = table[i] ; // points to the first
while (node != NULL) {
struct hashEntry* temp = node ;
node = node -> next ;
free (temp) ;
}
}
free(table) ;
}
bool containsDuplicate (int* nums, int numsSize) {
int tableSize = numsSize * 2 ;
struct hashEntry** hashTable = createHashTable(tableSize) ;
for (int i = 0 ; i < numsSize ; i++) {
if (search(hashTable, nums[i], tableSize)){
freeHashTable(hashTable, tableSize) ;
return true ;
}
insert(hashTable, nums[i], tableSize) ;
}
freeHashTable(hashTable, tableSize) ;
return false ;
}