-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwo_sum.cpp
58 lines (45 loc) · 1.31 KB
/
two_sum.cpp
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
/*
* @author: Swing
* @create: 2019-12-19 15:59
* @description: Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
*/
#define SIZE 50000
int hash(int key) {
int r = key % SIZE;
return r < 0 ? r + SIZE : r;
}
void insert(int *keys, int *values, int key, int value) {
int index = hash(key);
while (values[index]) {
index = (index + 1) % SIZE;
}
keys[index] = key;
values[index] = value;
}
int search(int *keys, int *values, int key) {
int index = hash(key);
while (values[index]) {
if (keys[index] == key) {
return values[index];
}
index = (index + 1) / SIZE;
}
return 0;
}
int* twoSum(int *nums, int numsSize, int target) {
int keys[SIZE];
int values[SIZE] = {0};
for (int i = 0; i < numsSize; i++) {
int complements = target - nums[i];
int value = search(keys, values, complements);
if (value) {
int *indices = (int *) malloc(sizeof(int) * 2);
indices[0] = value - 1;
indices[1] = i;
return indices;
}
insert(keys, values, nums[i], i + 1);
}
return NULL;
}