Started learning Rust by solving LeetCode problems as they involve all the standard data structures of the language. I have the following standard hash table solution to the two-sum problem:
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut positions = HashMap::<i32,usize>::new();
for (pos, n) in nums.iter().enumerate() {
positions.insert(*n, pos);
}
for (pos, n) in nums.iter().enumerate() {
if let Some(p) = positions.get(&(target - *n)) {
if *p != pos {
return vec![pos as i32, *p as i32];
}
}
}
return vec![];
}
}
In other words, the code returns two distinct indices into the vector such that the corresponding entries sum up to target.
The signature of the function is given by the platform. Since we are returning indices into the array, the return type should obviously be Vec<usize>
, so this is a dumb choice. Having to live with that, I'm trying to figure out two things:
- Since integers are trivial to copy, is there a way to write the code without having to deal with references?
HashMap::get()
seems to want a reference as its parameter. Is there a way to avoid the ugly&(target - *n)
when looking up positions in the hash table?- Any other Rust tips for making the code cleaner or more idiomatic?