Two Sum (LeetCode 1)
Solution for Two Sum in Rust
- Time complexity:
- Space complexity:
//! Author: https://github.com/dhruvildave
use std::collections::HashMap;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut h: HashMap<i32, usize> = HashMap::with_capacity(nums.len());
for (i, n) in nums.iter().enumerate() {
let diff = target - n;
if let Some(d) = h.get(&diff) {
return vec![*d as i32, i as i32];
}
h.insert(*n, i);
}
vec![-1, -1]
}
}