Skip to content

Instantly share code, notes, and snippets.

@AnjaliManhas
Created April 26, 2020 08:36
Show Gist options
  • Save AnjaliManhas/ae79e74ed4a8fd5446c1e1fe38b495db to your computer and use it in GitHub Desktop.
Save AnjaliManhas/ae79e74ed4a8fd5446c1e1fe38b495db to your computer and use it in GitHub Desktop.
Two Sum LeetCode- Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
class Solution {
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++) {
if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
return new int[]{i, map.get(target - nums[i])};
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment