-
Notifications
You must be signed in to change notification settings - Fork 0
/
two_sum.rs
72 lines (64 loc) · 2.42 KB
/
two_sum.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
1. Two Sum
-> LeetCode {easy}
Given an array of integers nums and an integer target, return indices of the two numbers such that
they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element
twice.
You can return the answer in any order.
*/
use std::io::{self, BufRead};
use std::collections::HashMap;
fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hm = HashMap::with_capacity(nums.len());
for (i, &num) in nums.iter().enumerate() {
match hm.get(&num) {
Some(&j) => return vec![i as i32, j as i32],
None => {
hm.insert(target - num, i);
},
}
}
unreachable!();
}
// fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
// let mut differences: HashMap<i32, i32> = HashMap::new();
// let start_idx;
// for (idx, value) in nums.iter().enumerate() {
// match differences.contains_key(&value) {
// true => {
// start_idx = differences.get(&value).unwrap();
// return vec![*start_idx as i32, idx as i32];
// },
// false => {
// differences.insert(target-value, idx as i32);
// },
// };
// }
// vec![-1, -1]
// }
fn main() {
let stdin = io::stdin();
let mut stdin_iterator = stdin.lock().lines();
let input_line: String = match stdin_iterator.next() {
Some(Ok(line)) => line,
_ => {
println!("Error reading vector input!");
return ;
},
};
let nums: Vec<i32> = input_line.trim()
.split(' ')
.filter(|s| !s.is_empty())
.map(|s| s.to_string().parse::<i32>().unwrap())
.collect();
let target: i32 = match stdin_iterator.next() {
Some(Ok(val)) => val.trim().parse::<i32>().unwrap(),
_ => {
println!("Error reading target input!");
return ;
}
};
let result = two_sum(nums, target);
println!("result : {:?}", result);
}