Given an array of integers, 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. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
直接遍历会超时,考虑到在一个有序数组中求此类问题是设置两个指针一个指向头一个指向尾,当和大了就把尾指针前移,小了把头指针后移复杂度为O(n),然后题目要求按下标在原数组中的位置输出,那么就遍历原数组得到两个数的下标即可。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res,tmp;
tmp = nums;
sort(tmp.begin(), tmp.end());
int i = 0, j = tmp.size()-1;
while(tmp[i]+tmp[j] != target){
if(tmp[i]+tmp[j] > target)
j--;
else
i++;
}
for(int k = 0; k < nums.size(); k++){
if(nums[k] == tmp[i])
res.push_back(k+1);
else if(nums[k] == tmp[j])
res.push_back(k+1);
}
return res;
}
};