- Published on
[LeetCode 1] Two Sum
Problem
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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up:
Can you come up with an algorithm that is less than O(n2) time complexity?
Thoughts
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
Code
Javascript
/**
* @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;
}
};
Typescript
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);
}
};
Ruby
# @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
Python
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
C++
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>{};
}
};
Go
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{}
}