Problem description:
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
Analysis:
The idea is maintain a hashtable for each element num in nums, using num
as key and its index as value. For each num, search for target - num in the hast table.
Time : 20ms.
vector<int> twoSum(vector<int> &numbers, int target)
{
unordered_map <int, int> mp;
int n = numbers.size();
for (int i = 0; i < n; ++i)
{
// if (mp[target - numbers[i]] > 0) //slower
if (mp.find(target - numbers[i]) != mp.end())
return {mp[target - numbers[i]], i + 1};
mp [numbers[i]] = i + 1;
}
}
We also can sort the array and index at the same time, then use two pointers to find the result pair.
Here I use custom Qsort. Time : 8ms
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> index;
int n = numbers.size();
for (int i = 0; i < n; ++i)
index.push_back(i);
Qsort(numbers, index, 0, n - 1);
int i = 0, j = n - 1, sum = 0;
while (i < j)
{
sum = numbers[i] + numbers[j];
if (sum == target)
return {min(index[i], index[j]) + 1, max(index[i], index[j]) + 1};
else if (sum > target) --j;
else ++i;
}
}
void Qsort (vector<int> & v1, vector<int> & v2, int low , int high)
{
int mid, key, i, j;
if (low < high) // to choose a better pivot.
{
mid = low + (high - low) / 2;
swap(v1[mid], v1[low]);
swap(v2[mid], v2[low]);
key = v1[low];
i = low + 1;
j = high;
while (i <= j)
{
while (i <= j && v1[i] <= key)
++i;
while (i <= j && v1[j] > key)
--j;
if (i < j)
{
swap(v1[i], v1[j]);
swap(v2[i], v2[j]);
}
}
swap(v1[low], v1[j]);
swap(v2[low], v2[j]);
Qsort(v1, v2, low, j - 1);
Qsort(v1, v2, j + 1, high);
}
}
};