Skip to content

Commit aaa3947

Browse files
authored
Create solution.rs
1 parent 90d3424 commit aaa3947

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

TwoSum/solution.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
}

0 commit comments

Comments
 (0)