class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
int n = nums.length;
//Building Hash
for (int i = 0; i < n; i++) {
numMap.put(nums[i], i);
}
//Finding complement
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement) && numMap.get(complement) != i) {
return new int[]{i, numMap.get(complement)};
}
}
//for no solution
return new int[]{};
}
}
Open to updates and suggestions.
Top comments (0)