#1.Two Sum [LeetCode Grind 75 in Rust]

Kallol BairagiKallol Bairagi
1 min read
use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut map_of_numbers = HashMap::with_capacity(nums.len());
        let mut ans: Vec<i32> = Vec::new();    

        for (i , &v) in nums.iter().enumerate() {
            let check = target - v;

            match map_of_numbers.get(&check){
                Some(&i2) => {
                    ans.push(i as i32);
                    ans.push(i2);
                    break;
                }
                None => {
                    map_of_numbers.insert(v, i as i32);
                }
            }
        } 
        ans
    }
}
10
Subscribe to my newsletter

Read articles from Kallol Bairagi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kallol Bairagi
Kallol Bairagi