Leetcode #167 两数之和Ⅱ 输入有序数组C++
双指针
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int low, high;
low = 0;
high = numbers.size() - 1;
while(low < high) {
if(numbers[low] + numbers[high] == target) {
return {low + 1, high + 1};
}
else if (numbers[low] + numbers[high] > target) {
high--;
}
else if(numbers[low] + numbers[high] < target) {
low++;
}
}
return{-1,-1};
}
};
Hash
两遍哈希
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i;
map<int,int> m;
for(i = 0; i < numbers.size(); i++) {
m[numbers[i]] = i;
}
for(i = 0; i < numbers.size(); i++) {
if(m.find(target - numbers[i]) != m.end() && m[target - numbers[i]] > i) {
return {i + 1, m[target - numbers[i]] + 1};
}
}
return {};
}
};
一遍哈希
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i;
map<int,int> m;
for(i = 0; i < numbers.size(); i++) {
if(m.find(target - numbers[i]) != m.end()) {
return {m[target - numbers[i]] + 1, i + 1};
}
m[numbers[i]] = i;
}
return {};
}
};