File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ use std:: collections:: HashMap ;
2
+
3
+ impl Solution {
4
+ pub fn two_sum ( nums : Vec < i32 > , target : i32 ) -> Vec < i32 >
5
+ {
6
+ let mut hashmap: HashMap < i32 , i32 > = HashMap :: new ( ) ;
7
+
8
+ for i in 0 ..nums. len ( )
9
+ {
10
+ let curNum = nums[ i] ;
11
+ let neededNum = target - curNum;
12
+
13
+ // check if needed value exists already in the hashmap
14
+ // return the indices of both value if it does
15
+ if ( hashmap. contains_key ( & neededNum) )
16
+ {
17
+ return [ i as i32 , * hashmap. get ( & neededNum) . unwrap ( ) ] . to_vec ( ) ;
18
+ }
19
+
20
+ // add current value mapped to current index to hashmap sp it can be queried later
21
+ hashmap. insert ( curNum, i as i32 ) ;
22
+ }
23
+
24
+ // Should never reach here because one solution is guaranteed
25
+ return [ ] . to_vec ( ) ;
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments