File tree 1 file changed +29
-0
lines changed
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ //LeetCode 1. Two Sum
2
+ //Question Link - https://leetcode.com/problems/two-sum/
3
+
4
+ class Solution {
5
+ public int [] twoSum (int [] nums , int target ) {
6
+ int result [] = new int [2 ];
7
+
8
+ //to store the numbers which have already been encountered
9
+ //key = number in array, value = index of the number
10
+ Map <Integer , Integer > seen = new HashMap <>();
11
+
12
+ for (int i = 0 ; i < nums .length ; i ++){
13
+ //the number nums[i] is alreday in the array
14
+ //check if (target - nums[i]) is also in the array or not
15
+ int complement = target - nums [i ];
16
+
17
+ //we check if we have already encountered complement or not.
18
+ if (seen .containsKey (complement )){
19
+ return new int []{seen .get (complement ), i };
20
+ }
21
+
22
+ //if complement does not exsist, we must store the current number in seen
23
+ //The current number could be the complement of some number to be visited further in the array
24
+ seen .put (nums [i ], i );
25
+ }
26
+
27
+ return result ;
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments