题目描述:
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.
Notice
You may assume that each input would have exactly one solution
numbers=[2, 7, 11, 15]
, target=9
return [1, 2]
Either of the following solutions are acceptable:
- O(n) Space, O(nlogn) Time
- O(n) Space, O(n) Time
这题仍然用了two pointers的思路。比较绕的地方是题目要求返回符合条件的element的index。这就需要在sort array前做一个备份,求出sorted array对应的index解之后再做mapping index。这里有两个特殊情况需要注意:
1. 当array中有两个相同的element
2. 求得的sorted array对应的index顺序可能与original array的index顺序相反。
这里我用了比较土的方法去map index:将array遍历两遍,同时用visited去存已经访问过的index,这样就避免了item 1中的情况,而遍历两遍也不会miss掉第二个index(当item 2的情况出现时)。
Mycode(AC = 12ms):
class Solution {
public:
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1+1, index2+1] (index1 < index2)
*/
vector<int> twoSum(vector<int> &nums, int target) {
// write your code here
vector<int> index(2, 0);
vector<int> sorted_index(2, -1);
vector<int> sorted_nums(nums);
sort(sorted_nums.begin(), sorted_nums.end());
// two pointer search for sorted array
int l = 0, r = sorted_nums.size() - 1;
while (l < r) {
if (sorted_nums[l] + sorted_nums[r] > target) {
r--;
}
else if (sorted_nums[l] + sorted_nums[r] < target) {
l++;
}
else {
sorted_index[0] = l;
sorted_index[1] = r;
break;
}
}
// [1,0,-1]
// [-1,0,1]
// map sorted index to original index
int visited = -1;
for (int k = 0; k < 2; k++) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == sorted_nums[sorted_index[k]] &&
visited != i + 1)
{
index[k] = i + 1;
visited = i + 1;
break;
}
}
}
sort(index.begin(), index.end());
return index;
}
};