I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
Here is my cpp solution with O(nlog(n)):
vector two_sum(vector &numbers, int target) {
vector result;
vector numbers_dup = vector(numbers);
sort(numbers_dup.begin(), numbers_dup.end());
int left = 0, right = numbers_dup.size() - 1;
while(left <= right) {
int sum = numbers_dup[left] + numbers_dup[right];
if(sum == target) {
//find the idex of numbers_dup[left] and numbers_dup[right]
for(int i = 0; i < numbers.size(); i++) {
if(numbers[i] == numbers_dup[left] || numbers[i] == numbers_dup[right]) {
result.push_back(i);
}
if(result.size() == 2) {
return result;
}
}
}
else if(sum > target) {
right--;
}
else {
left++;
}
}
}
Check out my blog for the detailed explanation. https://algorithm.pingzhang.io/Array/two_sum_problem.html