LeetCode Video LogoLeetCode Video
LeetCode Video
AboutContactPrivacyTerms
© 2024 LeetCode Video. All rights reserved.
Your browser does not support the video tag.

1. Two Sum

12 views
Easy
Hash

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.

1. Two Sum

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] Explanation: 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?

Solutions

cpp
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> numMap;
        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];
            if (numMap.find(complement) != numMap.end()) {
                return {numMap[complement], i};
            }
            numMap[nums[i]] = i;
        }
        return {};
    }
};
java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement)) {
                return new int[]{numMap.get(complement), i};
            }
            numMap.put(nums[i], i);
        }
        return new int[0];
    }
}
python3
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_map = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in num_map:
                return [num_map[complement], i]
            num_map[num] = i
        return []
python
class Solution:
    def twoSum(self, nums, target):
        num_map = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in num_map:
                return [num_map[complement], i]
            num_map[num] = i
        return []
javascript
var twoSum = function(nums, target) {
    const numMap = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (numMap.has(complement)) {
            return [numMap.get(complement), i];
        }
        numMap.set(nums[i], i);
    }
    return [];
};
typescript
function twoSum(nums: number[], target: number): number[] {
    const numMap = new Map<number, number>();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (numMap.has(complement)) {
            return [numMap.get(complement)!, i];
        }
        numMap.set(nums[i], i);
    }
    return [];
};
csharp
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        Dictionary<int, int> numDict = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++) {
            int complement = target - nums[i];
            if (numDict.ContainsKey(complement)) {
                return new int[] { numDict[complement], i };
            }
            numDict[nums[i]] = i;
        }
        return new int[0];
    }
}
c
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> numMap;
        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];
            if (numMap.find(complement) != numMap.end()) {
                return {numMap[complement], i};
            }
            numMap[nums[i]] = i;
        }
        return {};
    }
};
go
func twoSum(nums []int, target int) []int {
    numMap := make(map[int]int)
    for i, num := range nums {
        complement := target - num
        if idx, exists := numMap[complement]; exists {
            return []int{idx, i}
        }
        numMap[num] = i
    }
    return nil
}
kotlin
class Solution {
    fun twoSum(nums: IntArray, target: Int): IntArray {
        val numMap = mutableMapOf<Int, Int>()
        for (i in nums.indices) {
            val complement = target - nums[i]
            numMap[complement]?.let {
                return intArrayOf(it, i)
            }
            numMap[nums[i]] = i
        }
        return intArrayOf()
    }
}
swift
class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var numDict = [Int: Int]()
        for (i, num) in nums.enumerated() {
            let complement = target - num
            if let index = numDict[complement] {
                return [index, i]
            }
            numDict[num] = i
        }
        return []
    }
}
ruby
def two_sum(nums, target)
    num_map = {}
    nums.each_with_index do |num, i|
        complement = target - num
        if num_map.key?(complement)
            return [num_map[complement], i]
        end
        num_map[num] = i
    end
    []
end
php
class Solution {
    function twoSum($nums, $target) {
        $numMap = [];
        foreach ($nums as $i => $num) {
            $complement = $target - $num;
            if (array_key_exists($complement, $numMap)) {
                return [$numMap[$complement], $i];
            }
            $numMap[$num] = $i;
        }
        return [];
    }
}
scala
object Solution {
    def twoSum(nums: Array[Int], target: Int): Array[Int] = {
        import scala.collection.mutable.Map
        val numMap = Map[Int, Int]()
        for (i <- nums.indices) {
            val complement = target - nums(i)
            if (numMap.contains(complement)) {
                return Array(numMap(complement), i)
            }
            numMap(nums(i)) = i
        }
        Array()
    }
}

Related Problems

More related problems will appear here.