-
Notifications
You must be signed in to change notification settings - Fork 0
/
167_c
42 lines (38 loc) · 956 Bytes
/
167_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
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
vector<int> output;
for (int i = 0; i < numbers.size(); i++) {
for (int j = 0; j < res.size(); j++) {
if (numbers[i] == res[j]) {
output.push_back(j + 1);
output.push_back(i + 1);
return output;
}
}
res.push_back(target - numbers[i]);
}
return output;
}
};
It's a binary search problem
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0, right = numbers.size() - 1;
vector<int> res;
while(left < right){
long long val = numbers[left] + numbers[right];
if(val == target){
res.push_back(left + 1);
res.push_back(right + 1);
break;
}else if(val < target)
left++;
else
right--;
}
return res;
}
};