The following code works:
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map = std::collections::HashMap::new();
for (i, x) in nums.iter().enumerate(){
if map.contains_key(target -x ) {
return vec![map[x] as i32, i as i32];
} else {
map.insert(x, i);
}
}
}
But the following does not work:
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut map = std::collections::HashMap::new();
for (i, x) in nums.iter().enumerate(){
if map.contains_key(x) {
return vec![map[x] as i32, i as i32];
} else {
map.insert(target-x, i);
}
}
}
Why does map.contains_key(x) work but map.contains_key(target-x) gives an error?
Update: added the function signature.
Because contains_key()
takes a reference parameter. I'm guessing nums
is a vector or slice, so x
is a reference because it came from iter()
, vs. something like into_iter()
. But target-x
creates a new value , so you'll need to wrap it like contains_key(&(target - x))
.
What @cuviper said was pretty clear also from the rustc
compilation error message:
error[E0308]: mismatched types
--> src/lib.rs:4:29
|
4 | if map.contains_key(target - x) {
| ^^^^^^^^^^
| |
| expected reference, found `i32`
| help: consider borrowing here: `&(target - x)`
|
= note: expected reference `&_`
found type `i32`
It's easier to make sense of the error after understanding the difference between iter() and into_iter(). Thanks.
1 Like
system
Closed
October 17, 2020, 9:24pm
6
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.