Skip to content

Instantly share code, notes, and snippets.

@imsurajmishra
Last active August 30, 2021 00:18
Show Gist options
  • Save imsurajmishra/133d0729b8044c1657a5bda150924af3 to your computer and use it in GitHub Desktop.
Save imsurajmishra/133d0729b8044c1657a5bda150924af3 to your computer and use it in GitHub Desktop.
Leetcode Problem # 1
//problem -> https://leetcode.com/problems/two-sum/
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2]; // this is result array which stores indices of two numbers
Map<Integer, Integer> map = new HashMap<>(); // map to store number and its indices
for(int i=0;i<nums.length;i++){ // put number and indices into hashmap
map.put(nums[i], i);
}
for(int i=0;i<nums.length;i++){ // traverse element in the array
if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i){ // Check diff = target-num exist in the hashmap if exist check if its reffering input_y
int index = map.get(target-nums[i]); // get the index of target_x
result[0]=i; // store index(input_y)
result[1]=index; // store index(input_x)
break;
}
}
return result; // return the result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment