Two Sum in Rust

impl Solution {
    // Define a public function `two_sum` that takes a vector of i32 (`nums`) and a single i32 (`target`)
    // and returns a vector of i32. This function aims to find two indices of the numbers in `nums`
    // that add up to `target`.
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        // Import HashMap from the Rust standard collections library into the scope for easy use.
        use std::collections::HashMap;

        // Create a mutable HashMap named `m` to store the value and index of elements from `nums`.
        // Keys are the numbers from the `nums` vector, and values are their respective indices.
        let mut m: HashMap<i32, i32> = HashMap::new();

        // Iterate over the numbers in `nums` with their index. `enumerate` provides a tuple containing
        // the index and the value.
        for (i, v) in nums.iter().enumerate() {
            // Check if the complement (target - current value) exists in the map.
            // If it does, it means a previous number in the array can be added to the current number
            // to reach the target.
            match m.get(&(target - *v)) {
                // If a complement is found, return a vector containing the current index and the
                // index of the complement. This is the solution: indices of the two numbers that add up to `target`.
                Some(&i2) => return vec![i as i32, i2],

                // If no complement is found, insert the current value and its index into the map
                // for future reference. `None` branch of the match statement means no entry was found.
                None => m.insert(*v, i as i32),
            };
        }

        // If no pair adds up to the target, return an empty vector.
        // This line is reached if the loop completes without returning.
        vec![]
    }
}

PrevNext