-
Notifications
You must be signed in to change notification settings - Fork 1
/
1.cpp
50 lines (48 loc) · 920 Bytes
/
1.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
class Solution {
private:
int *hash;
int *idx;
int q;
public:
void push(int x, int i) {
int key = ((x % q) * (x % q)) % q;
while (idx[key] >= 0) {
key = (key + 1) % q;
}
hash[key] = x;
idx[key] = i;
}
int find(int x) {
int key = ((x % q) * (x % q)) % q;
while (hash[key] != x) {
if (idx[key] < 0) {
return -1;
}
key = (key + 1) % q;
}
return idx[key];
}
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
res.clear();
q = (nums.size() << 1) + 1;
hash = new int[q];
idx = new int[q];
memset(hash, 0xff, sizeof(int) * q);
memset(idx, 0xff, sizeof(int) * q);
for (int i = 0; i < nums.size(); i++) {
push(nums[i], i);
}
for (int i = 0; i < nums.size(); i++) {
int j = find(target - nums[i]);
if (j >= 0 && j != i) {
res.push_back(i);
res.push_back(j);
break;
}
}
delete[] hash;
delete[] idx;
return res;
}
};