-1

Here's my code to find the indices of two numbers such that they add up to a specific target:

use std::collections::HashMap;

fn two_sum(nums: &[i32], target: i32) -> [usize;2] {
    let mut map: HashMap<i32, usize>  = HashMap::new();

   for i in  0..nums.len() {
        let want = target - nums[i];
        match map.get(&nums[i]) {
            Some(&seen) => return [seen, i],
            _ =>  map.insert(want, i),
            };
    }

    [0usize, 0usize];
}

fn main() {
    let nums = [1,3,7,4];
    let res = two_sum(&nums, 10);
    println! ("{},{}", res[0], res[1]);
}

Which throws this error:

src/bin/2sum.rs:3:1: 15:2 error: not all control paths return a value [E0269]
src/bin/2sum.rs:3 fn two_sum(nums: &[i32], target: i32) -> [usize;2] {
src/bin/2sum.rs:4     let mut map: HashMap<i32, usize>  = HashMap::new();
src/bin/2sum.rs:5 
src/bin/2sum.rs:6     for i in  0..nums.len() {
src/bin/2sum.rs:7         let want = target - nums[i];
src/bin/2sum.rs:8         match map.get(&nums[i]) {
              ...
src/bin/2sum.rs:3:1: 15:2 help: run `rustc --explain E0269` to see a detailed     explanation
error: aborting due to previous error

How can I solve this problem?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Min Zhou
  • 118
  • 5

1 Answers1

3

You can remove the semicolon after [0usize, 0usize] (this is idiomatic) or add a return [0usize, 0usize].

To improve your code you can return an Option. Also, in this case, it is better to return a tuple.

use std::collections::HashMap;

fn two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
    let mut map: HashMap<i32, usize> = HashMap::new();

    for i in 0..nums.len() {
        let want = target - nums[i];
        match map.get(&nums[i]) {
            Some(&seen) => return Some((seen, i)),
            _ => map.insert(want, i),
        };
    }

    None
}

fn main() {
    let nums = [1, 3, 7, 4];
    let res = two_sum(&nums, 10);
    println!("{:?}", res);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
malbarbo
  • 10,717
  • 1
  • 42
  • 57