Last active
August 30, 2021 00:18
-
-
Save imsurajmishra/133d0729b8044c1657a5bda150924af3 to your computer and use it in GitHub Desktop.
Leetcode Problem # 1
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
//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