classSolution { publicint[] twoSum(int[] nums, int target) { for(inti=0; i < nums.length; i++) { for(intj= i + 1; j < nums.length; j++) { if (i != j){ if (nums[i] + nums[j] == target){ returnnewint[]{i, j}; } } } } returnnewint[]{0,0}; } }
TC: $O(n^2)$
Remarks:
check the range of j: j will always be greater than i.
be careful of array index bound
Two-pass Hash Table
Check if the complement is in the array.
Steps:
create the hash table
find complmenet = target - num[i] in the hash table
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = newHashmap<>(); for (inti=0; i < nums.length; i++) { map.put(nums[i], i); } for (inti=0; i < nums.length; i++) { intcomplement= target - nums[i]; if (map.containskey(complement) && map.get(complement) != i) { returnnewint[] { i, map.get(complement) }; } }
returnnewint[] { 0, 0 }; } }
Remarks:
containsKey with capital K
create java map
TC: $O(n)$
SC: $O(n)$
HashMap in Java
Insert key pairs: map.put(num1,num2)
Get a key: map.get(num)
Check if contain a key: map.containsKey(num)
Delete key: map.remove(key)
Get size: map.size()
Iterate: for (Map.Entry<K, V> entry : map.entrySet())
How Java did hashcode()?
By default, Object.hashCode() returns an integer derived from the object’s memory address (or a JVM-specific identity), potentially mixed to improve hash uniformity.
One-pass Hash Table
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = newHashMap<>(); for (inti=0; i < nums.length; i++) { intcomplement= target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { returnnewint[] { i, map.get(complement) }; } map.put(nums[i], i); } returnnewint[] { 0, 0 }; } }
Remarks:
only put the value into the map after checking the key