Last active
December 3, 2019 18:18
-
-
Save psy901/043096ba05b0c15296bcb2d7e2997d27 to your computer and use it in GitHub Desktop.
LeetCode #2 Two Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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