-
Notifications
You must be signed in to change notification settings - Fork 0
/
167.Two-Sum-II-Input-Array-Is-Sorted.cpp
45 lines (44 loc) · 1.16 KB
/
167.Two-Sum-II-Input-Array-Is-Sorted.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
// O(nLogn)
class Solution {
public:
int binarySearch(int start, int target, vector<int>&nums){
int l = start, r = nums.size() - 1;
while(l <= r){
int mid = l + (r - l)/2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> ans(2);
for(int i = 0; i < nums.size() - 1; i++){
int other = binarySearch(i + 1, target - nums[i], nums);
if(other != -1){
ans[0] = i + 1;
ans[1] = other + 1;
break;
}
}
return ans;
}
};
//O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i = 0, j = nums.size() - 1;
vector <int> ans(2);
while(i < j){
if(nums[i] + nums[j] == target){
ans[0] = i + 1;
ans[1] = j + 1;
break;
}
else if(nums[i] + nums[j] < target) i++;
else j--;
}
return ans;
}
};