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.
Examples
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]
Analysis
We can solve it by two for loop and this solution will take O(n^2) time complexity and O(1) space complexity. Fortunately, we can use a hash table to save the pair that target-nums[i] as key and i as value and find the key if exists in in nums. This solution will take O(n) time complexity but O(n) space complexity.
publicclassSolution { publicint[] TwoSum(int[] nums, int target) { int[] res = newint[2]; Dictionary<int,int> dict = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { if(dic.TryGetValue(target - nums[i], outintvalue)) // O(1) { res[1] = i; res[0] = value; break; } if (!dic.ContainsKey(nums[i])) // O(1) { dic.Add(nums[i], i); } } return res; } }
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ int size = nums.size(); unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < size; i++) { int numberToFind = target - nums[i]; if (hash.contains(numberToFind)) { result.push_back(hash[numberToFind]); result.push_back(i); return result; } hash[nums[i]] = i; } return result; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: deftwoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ iflen(nums) <= 1: returnFalse buff_dict = {} for i inrange(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i
Rust
1 2 3 4 5 6 7 8 9 10 11 12 13 14
use std::collections::HashMap; implSolution { pubfntwo_sum(nums: Vec<i32>, target: i32) ->Vec<i32> { letmut hash = HashMap::new(); for (index, value) in nums.iter().enumerate() { letnumber_to_find = target - *value; if hash.contains_key(&number_to_find) { returnvec![hash[&number_to_find], index asi32]; } hash.insert(value, index asi32); } returnvec![]; } }
Javascript
1 2 3 4 5 6 7 8 9 10 11
var twoSum = function (nums, target) { var hash = {}; for (let i = 0; i < nums.length; i++) { let index = hash[target - nums[i]]; if (typeof index !== "undefined") { return [index, i]; } hash[nums[i]] = i; } returnnull; };
// 1.Two Sum functwoSum(nums []int, target int) []int { hashTable := map[int]int{} for i, x := range nums { if p, ok := hashTable[target-x]; ok { return []int{p, i} } hashTable[x] = i } returnnil }