First thought: given that there exists exactly one solution -> use of complement (calculate and store complement value as key and index in nums array as value). To look up the complement value, time complexity minimized using HashMap (O(1) lookup time). however, this solution iterates through the nums array twice (once to populate hashmap, second to find index pairs).
My solution:
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
map.putIfAbsent(target-nums[i], i);
}
for (int i=0; i<nums.length; i++) {
if (map.get(nums[i])!=null && map.get(nums[i])!=i) {
return new int[] {i, map.get(nums[i])};
}
}
return new int[] {-1, -1};
}
}
Improved Solution: same in that it uses HashMap, but only one pass needed
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
int complement = target - nums[i];
int pairIndex = map.get(complement);
if (pairIndex!=null) return new int[] {pairIndex, i};
map.put(nums[i], i);
}
return null;