Find Pair Summing To Target

Locate the first pair adding up to a target in one pass, remembering seen values in a HashMap instead of rescanning the slice.

RustData Integrity

Code

rustsnippet
31 lines
use std::collections::HashMap;

// 一次遍历:对每个值查“补数”是否已见过,O(n) 完成
fn find_pair(values: &[i64], target: i64) -> Option<(usize, usize)> {
    let mut seen: HashMap<i64, usize> = HashMap::new();
    for (index, value) in values.iter().enumerate() {
        let complement = target - value;
        if let Some(&other) = seen.get(&complement) {
            return Some((other, index));
        }
        seen.insert(*value, index);
    }
    None
}

fn main() {
    let prices = [40, 25, 60, 35, 10];

    println!("pair summing 60: {:?}", find_pair(&prices, 60));
    println!("pair summing 95: {:?}", find_pair(&prices, 95));
    println!("pair summing 999: {:?}", find_pair(&prices, 999));

    // 重复值也能配对:25 + 25 = 50,两次出现位置不同
    let repeats = [25, 25];
    println!("pair summing 50: {:?}", find_pair(&repeats, 50));

    // 返回的是下标对:可以拿回原始值
    if let Some((i, j)) = find_pair(&prices, 60) {
        println!("values: {} + {} = 60", prices[i], prices[j]);
    }
}

How it works

Find Pair Summing To Target comes down to the functions find_pair and main.

A single loop drives the file — for (index, value) in values.iter().enumerate().

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: fn find_pair(values: &[i64], target: i64) -> Option<(usize, usize)>

Running the file prints labeled results such as pair summing 60:, pair summing 95:, pair summing 999: — each operation’s effect is visible in the output.

Running the file executes main, which drives find_pair in order.

Key statements

return Some((other, index));
if let Some((i, j)) = find_pair(&prices, 60) {
println!("values: {} + {} = 60", prices[i], prices[j]);
}

Interactive Tools for This Topic

FAQ

What does Find Pair Summing To Target print when run?
Invoke the file as-is — the `pair summing 60:`, `pair summing 95:`, `pair summing 999:` prefixes identify which step printed each line.