Created
August 24, 2023 10:30
-
-
Save vamsitallapudi/7a027af822c0c5b693dbed3ab6093b83 to your computer and use it in GitHub Desktop.
TwoSum problem solution in Java
This file contains hidden or 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<>(); // to store diff, position as key-value pair | |
int[] ans = new int[2]; | |
for(int i = 0; i< nums.length; i++) { | |
if(map.containsKey(nums[i])) { | |
ans[0] = map.get(nums[i]); | |
ans[1] = i; | |
return ans; | |
} else { | |
map.put(target - nums[i], i); | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment