This is an easy level LeetCode question, obviously not much code to review. I'm posting C++/Java/Python here. If you'd like to review, please do so. Thank you!
Problem
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
C++
class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { unordered_map<int, int> index_map; for (int index = 0;; index++) { auto iter = index_map.find(target - nums[index]); if (iter != index_map.end()) return vector<int> {index, iter -> second}; index_map[nums[index]] = index; } } };
Java
class Solution { public int[] twoSum(int[] nums, int target) { int[] indices = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int index = 0; index < nums.length; index++) { if (map.containsKey(target - nums[index])) { indices[1] = index; indices[0] = map.get(target - nums[index]); return indices; } map.put(nums[index], index); } return indices; } }
Python
class Solution: def twoSum(self, nums, target): index_map = {} for index, num in enumerate(nums): if target - num in index_map: return index_map[target - num], index index_map[num] = index