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. 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
给定一个排序好的数组和一个目标数,需要在数组中找到两个相加等于目标数的元素位置。之前也有一道Two Sum的题,不过那个并没有对数组进行排序。所以未排序版本的解法在这里依然是适用的。
未排序版的解题方法,可以参考:Two Sum。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
unordered_map<int,int> m;
if (!nums.empty()) {
int i;
for (i = 0; i < nums.size(); i++) {
//if (m.find(nums[i]) == m.end()) {//此时map中不存在此hash
if(!m.count(nums[i])) {
m[target-nums[i]] = i;
} else {
ret.push_back(m[nums[i]] + 1);//另一个的下标索引
ret.push_back(i + 1);//此时的下标索引
return ret;
}
}
}
return ret;
}
};
但是既然是排序的了,那么肯定可以利用排序这个规则。可以设置两个变量start和end,start从数组前面向后面移动,end则从后面向前面移动。如果start和end位置上的元素之和等于目标数,那么就返回这两个位置,如果小于目标数则让start向后移动,如果大于目标数则让end向前移动。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
int start = 0;//从头开始查找
int end = nums.size() - 1;//从尾部开始查找
int sum;//记录start位置和end位置的和
while(start < end) {//从两边开始向中间靠近
sum = nums[start] + nums[end];
if(sum == target) {//如果此时相等,则说明找到了正确的位置
ret.push_back(start + 1);
ret.push_back(end + 1);
break;
} else if (sum < target) {//如果两个位置之和小于目标数,则让start向后移动一位
start++;
} else {//否则让end向前移动一位
end--;
}
}
return ret;
}
};