One Pass HashMap - O(n) time, O(n) space (3ms, 99.76%)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
int num = nums[i];
if(map.containsKey(target - num)) {
return new int[] {map.get(target - num), i};
}
map.put(num, i);
}
return new int[]{1,1};
}
}
Brute Force - Two Loops - O(n^2) time, O(1) space
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
Two Pass Hash Table: O(n) time, O(n) space - (8ms 56.82%)
Beware that the complement must not be nums[i] itself!
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}