Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to implement the two sum algorithm to find two values in vector that add up to target with Rust

1 Answer

0 votes
fn two_sum(vec: &[i32], target: i32) -> Option<(usize, usize)> {
    for i in 0..vec.len() {
        for j in (i + 1)..vec.len() {
            if vec[i] + vec[j] == target {
                return Some((i, j)); // Return indices as a tuple
            }
        }
    }
    None // Return None if no valid pair is found
}

fn main() {
    let vec1 = vec![1, 5, 7, 4, 3, 2];
    let vec2 = vec![3, 1, 4, 2, 5];

    // Finding pairs
    match two_sum(&vec1, 9) {
        Some((i, j)) => println!("Indices: ({}, {}), Numbers: ({}, {})", i, j, vec1[i], vec1[j]),
        None => println!("No matching pair found."),
    }

    match two_sum(&vec2, 8) {
        Some((i, j)) => println!("Indices: ({}, {}), Numbers: ({}, {})", i, j, vec2[i], vec2[j]),
        None => println!("No matching pair found."),
    }
}

  
   
/*
run:
   
Indices: (1, 3), Numbers: (5, 4)
Indices: (0, 4), Numbers: (3, 5)
   
*/

 

 



answered May 22, 2025 by avibootz
...