Created
April 26, 2020 08:36
-
-
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.
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) { | |
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