Given an array of integers, return indices of the two numbers such that they add up to a specific target. See it on Leetcode
1
2
3
4
For example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
It should return [0, 1].
Hint
You may assume that each input would have exactly one solution.
Solution #1 Brute Force - 38ms / 59ms
java
go
1 2 3 4 5 6 7 8 9 10 11 12
publicclassSolution{ publicint[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { returnnewint[]{i, j}; } } } returnnewint[]{0, 0}; } }
1 2 3 4 5 6 7 8 9 10
functwoSum(nums []int, target int) []int { for i := 0; i < len(nums) - 1; i++ { for j := i + 1; j < len(nums); j++ { if nums[i] + nums[j] == target { return []int{i, j} } } } return []int{0, 0} }
Solution #2 One-pass Hash Table - 7ms / 9ms
java
go
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution{ publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { returnnewint[]{map.get(complement), i}; } map.put(nums[i], i); } thrownew IllegalArgumentException("No two sum solution"); } }
1 2 3 4 5 6 7 8 9 10 11 12
functwoSum(nums []int, target int) []int { m := make(map[int]int) for i := range nums { complement := target - nums[i] elem, ok := m[complement] if ok { return []int{elem, i} } m[nums[i]] = i } return []int{0, 0} }