Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Created August 24, 2023 10:30
Show Gist options
  • Save vamsitallapudi/7a027af822c0c5b693dbed3ab6093b83 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/7a027af822c0c5b693dbed3ab6093b83 to your computer and use it in GitHub Desktop.
TwoSum problem solution in Java
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