Published Sep 29, 2021
[
 
]
Given an array of integers nums
and an integer target
, return indices of the
two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Can you come up with an algorithm that is less than O(n2) time complexity?
Normally, array problems can be solved with the help of hash to speed up. So in
this case, we can have a valueToIndex
hash to store the value as we loop
through the array and check for solution
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const valueToIndex = {};
for(let i = 0; i < nums.length; i++){
if (valueToIndex[target - nums[i]] !== undefined){
return [i, valueToIndex[target - nums[i]]]
}
valueToIndex[nums[i]] = i;
}
};
function twoSum(nums: number[], target: number): number[] {
let valueToIndex = new Map();
for(let index = 0; index < nums.length; index++){
if(valueToIndex.has(target - nums[index])) {
return [index, valueToIndex.get(target - nums[index])];
}
valueToIndex.set(nums[index], index);
}
};
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
valueToIndex = {}
nums.each_with_index do |value, index|
if valueToIndex.key?(target - value)
return [index, valueToIndex[target - value]]
end
valueToIndex[value] = index;
end
end
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
valueToIndex = {}
for index, value in enumerate(nums):
if((target - value) in valueToIndex):
return [index, valueToIndex[target - value]]
valueToIndex[value] = index
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> valueToIndex;
for(auto index = 0; index < nums.size(); index++){
if(valueToIndex.find(target - nums[index]) != valueToIndex.end()){
return vector<int>{index, valueToIndex[target - nums[index]]};
}
valueToIndex[nums[index]] = index;
}
return vector<int>{};
}
};
func twoSum(nums []int, target int) []int {
var valueToIndex = make(map[int]int)
for index, value := range nums {
if secondIndex, ok := valueToIndex[target - value]; ok {
return []int{index, secondIndex}
}
valueToIndex[value] = index;
}
return []int{}
}