-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.rs
More file actions
51 lines (42 loc) · 1.48 KB
/
two_sum.rs
File metadata and controls
51 lines (42 loc) · 1.48 KB
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
use std::collections::HashMap;
pub struct Solution;
impl Solution {
// Approach 1: Brute Force
pub fn two_sum_brute_force(nums: Vec<i32>, target: i32) -> Vec<i32> {
for x in 0..nums.len() {
for y in x + 1..nums.len() {
if nums[x] + nums[y] == target {
return Vec::from([x as i32, y as i32]);
}
}
}
Vec::from([0, 0])
}
// Approach 2: Two-pass Hash Table
pub fn two_sum_two_pass_hashmap(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hashmap = HashMap::new();
for (index, value) in nums.iter().enumerate() {
hashmap.insert(value, index);
}
for (index, value) in nums.iter().enumerate() {
let complement = target - value;
if hashmap.contains_key(&complement) && hashmap[&complement] != index {
return Vec::from([index as i32, hashmap[&complement] as i32]);
}
}
Vec::new()
}
// Approach 3: One-pass Hash Table
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut hashmap = HashMap::new();
for (index, value) in nums.iter().enumerate() {
let complement = target - value;
if hashmap.contains_key(&complement) {
return Vec::from([hashmap[&complement] as i32, index as i32]);
} else {
hashmap.insert(value, index);
}
}
Vec::new()
}
}