-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_Two Sum.cpp
40 lines (30 loc) · 1.01 KB
/
1_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
// refer to discussion of Leetcode
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> table;
vector<int> ans;
for ( int i = 0; i < nums.size(); i++ ) {
if ( table.count(target-nums[i]) ) {
ans.push_back( table[target-nums[i]]+1 );
ans.push_back( i+1 );
return ans;
}
table[nums[i]] = i;
}
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// if the array is sorted and just find the numbers
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size(), l = 0, r = n - 1;
while (l < r) {
if (numbers[l] + numbers[r] == target)
return {l + 1, r + 1};
if (numbers[l] + numbers[r] > target) r--;
else l++;
}
}
};