Version 1:
A simple nested for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
var twoSum = function(nums, target) { for (let i = 0;i<nums.length ;i++){ let tmp = target - nums[i] for (let j = i+1;j<nums.length;j++){ if(tmp === nums[j]){ return [i,j] } } } };
|
Version 2:
HashMap have much better search time than a normal queue loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
var twoSum = function(nums, target) { const map = new Map() for (let i = 0; i< nums.length;i++){ const num = nums[i] const difference = target - num if (map.has(num)){ return [map.get(num), i] } map.set(difference, i) } };
|
Version 2.5 Java
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Solution { public static int[] twoSum(int[] nums, int target) { Map<Integer , Integer> map = new HashMap<Integer,Integer>(); for(int i = 0 ; i < nums.length ; i++) { int targetTemp = target - nums[i]; if(map.containsKey(targetTemp)) { return new int[] { map.get(targetTemp) , i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No solution"); } }
|