File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+
3+ class Solution {
4+ public int [] twoSum (int [] nums , int target ) {
5+ // Approach : using HashMap to get index with the element in O(n) time complexity
6+ // SpaceComplexity is also O(n)
7+ HashMap <Integer ,Integer > numIndexMap = new HashMap <Integer ,Integer >();
8+
9+ // Make key and value HashMap
10+ for (int i = 0 ; i < nums .length ; i ++){
11+ int num = nums [i ];
12+ numIndexMap .put (num ,i );
13+ }
14+
15+ // Search for the other operand looping nums
16+ for (int i = 0 ; i < nums .length ; i ++){
17+ int num = nums [i ];
18+ int operand = target - num ;
19+ Integer index = numIndexMap .get (operand );
20+ boolean indexExists = index != null ;
21+ boolean indexExistsAndIndexIsNotTheNum = indexExists && i != index ;
22+ if (indexExistsAndIndexIsNotTheNum ){
23+ // Manual sort
24+ if ( i < index ){
25+ return new int []{ i , index };
26+ }else {
27+ return new int []{ index , i };
28+ }
29+ }
30+ }
31+
32+ // If the valid answer is always exists this is not needed
33+ // But the compiler don't know about that
34+ return new int [2 ];
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments