-
Notifications
You must be signed in to change notification settings - Fork 0
/
1_two_sum.c
100 lines (88 loc) · 2.36 KB
/
1_two_sum.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*************************************************************************
> File Name: 1_two_sum.c
> Author: Tingjian Lau
> Mail: [email protected]
> Created Time: 2016/05/17
************************************************************************/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct HashNode {
int key;
int val;
} HashNode;
typedef struct HashMap {
int size;
HashNode** storage;
} HashMap;
HashMap* hash_create(int size);
void hash_destroy(HashMap* hashMap);
void hash_set(HashMap* hashMap, int key, int value);
HashNode* hash_get(HashMap* hashMap, int key);
HashMap* hash_create(int size){
HashMap* hashMap = malloc(sizeof(HashMap));
hashMap->size = size;
hashMap->storage = calloc(size, sizeof(HashNode*));
return hashMap;
}
void hash_destroy(HashMap* hashMap) {
for(int i; i < hashMap->size; i++) {
HashNode *node;
if((node = hashMap->storage[i])) {
free(node);
}
}
free(hashMap->storage);
free(hashMap);
}
void hash_set(HashMap *hashMap, int key, int value) {
int hash = abs(key) % hashMap->size;
HashNode* node;
while ((node = hashMap->storage[hash])) {
if (hash < hashMap->size - 1) {
hash++;
} else {
hash = 0;
}
}
node = malloc(sizeof(HashNode));
node->key = key;
node->val = value;
hashMap->storage[hash] = node;
}
HashNode* hash_get(HashMap *hashMap, int key) {
int hash = abs(key) % hashMap->size;
HashNode* node;
while ((node = hashMap->storage[hash])) {
if (node->key == key) {
return node;
}
if (hash < hashMap->size - 1) {
hash++;
} else {
hash = 0;
}
}
return NULL;
}
int* twoSum(int* nums, int numsSize, int target) {
HashMap* hashMap;
HashNode* node;
int rest, i;
int* result = malloc(sizeof(int)*2);
// make the hashMap 2x size of the numsSize
hashMap = hash_create(numsSize * 2);
for(i = 0; i < numsSize; i++) {
rest = target - nums[i];
node = hash_get(hashMap, rest);
if (node) {
result[0] = node->val;
result[1] = i;
hash_destroy(hashMap);
break;
} else {
hash_set(hashMap, nums[i], i);
}
}
return result;
}