Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
题目解析:
给出一个数组(升序)和一个目标数,求数组中的两个数相加正好等于目标数的两个元素的下标
思路:
- 1、因为同样也是求两数之和,所以可以使用之前的做法,利用hashmap来查找元素下标,hash表中数组的值作为key,数组值的索引作为value。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
if(target<numbers[0])return res;
unordered_map<int ,int> hash;
for(int i=0;i<numbers.size();i++)
{
int numberToFind=target-numbers[i];
if(hash.find(numberToFind)!=hash.end()){
res.push_back(hash[numberToFind]+1);
res.push_back(i+1);
return res;
}
hash[numbers[i]]=i;
}
return res;
}
};
- 2、因为给定的数组是有序的,所以可以利用二分法来搜索。开始时定义两个变量left和right分别指向数组的首末端,然后设立循环条件left<right(二分法的条件一般都是这个)。
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res;
int left=0;
int right=numbers.size()-1;
while(left<right)
{
int tmp=numbers[left]+numbers[right];
if(tmp==target)
{
res.push_back(left+1);
res.push_back(right+1);
return res;
}
else if(tmp<target)
left++;
else right--;
}
return res;
}
};