文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Two Sum II - Input array is sorted2. Solution
- Version 1
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int size = numbers.size();
vector<int> result;
for(int i = 0; i < size - 1; i++) {
for(int j = i + 1; j < size; j++) {
if(numbers[i] + numbers[j] == target) {
result.push_back(i + 1);
result.push_back(j + 1);
return result;
}
}
}
return result;
}
};
- Version 2
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int size = numbers.size();
vector<int> result;
for(int i = 0; i < size - 1; i++) {
int other = binarySearch(numbers, i + 1, size - 1, target - numbers[i]);
if(other != - 1) {
result.push_back(i + 1);
result.push_back(other + 1);
return result;
}
}
return result;
}
private:
int binarySearch(vector<int>& numbers, int left, int right, int target) {
while(left <= right) {
int middle = (left + right) / 2;
if(numbers[middle] == target) {
return middle;
}
else if(numbers[middle] > target) {
right = middle - 1;
}
else {
left = middle + 1;
}
}
return -1;
}
};
网友评论