# My cpp and javascript solution

• ``````vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
vector<int> numbers_dup = vector<int>(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++;
}
}
}
``````
``````var twoSum = function(nums, target) {
var value_index_hash = nums.reduce(function(previsou_value, current_value, index) {
previsou_value[current_value] = index;
return previsou_value;
}, {});

var result = [];
nums.some(function(current_value, index) {
var difference = target - current_value;
if(difference in value_index_hash && value_index_hash[difference] != index) {
result = [index, value_index_hash[difference]];
return true;
}
});
return result;
};
``````

Check out my blog for detailed explanation. https://algorithm.pingzhang.io/Array/two_sum_problem.html

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.