Skip to content

Instantly share code, notes, and snippets.

@psy901
Last active December 3, 2019 18:18
Show Gist options
  • Save psy901/043096ba05b0c15296bcb2d7e2997d27 to your computer and use it in GitHub Desktop.
Save psy901/043096ba05b0c15296bcb2d7e2997d27 to your computer and use it in GitHub Desktop.
LeetCode #2 Two Sum
class Solution {
public int[] twoSum(int[] nums, int target) {
// 1. initialize HashMap for {Number -> Index}
Map<Integer, Integer> map = new HashMap<>();
// 2. iterate the array
for (int i = 0; i < nums.length; i ++) {
// 3. check if such 'num2' exists in the hashmap
int num2 = target - nums[i];
if (map.containsKey(num2)) {
return new int[]{i, map.get(num2)};
}
// 4. if not exist, add new pair
map.put(nums2, i);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment