Skip to content

Commit 2a1a3c3

Browse files
committed
two sum解答
1 parent d0ede8c commit 2a1a3c3

File tree

1 file changed

+38
-28
lines changed

1 file changed

+38
-28
lines changed

src/two_sum.rs

Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,55 @@
11
pub struct Solution;
22
impl Solution {
33
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
4-
// インデックスをつけてタプルにする
5-
// index, valueの順番にする
6-
let nums_with_index: Vec<(usize, i32)> = nums.into_iter().enumerate().collect();
4+
// ハッシュマップを作成
5+
// キー→数値、値→インデックス
6+
let mut hash_map: std::collections::HashMap<i32, i32> = std::collections::HashMap::new();
77

8-
// target以上の値を持つ要素を取り除く
9-
let nums_with_index: Vec<(usize, i32)> = nums_with_index
10-
.into_iter()
11-
.filter(|(_, num)| *num < target)
12-
.collect();
13-
14-
// target - xにした
15-
16-
// target - xにした配列を作る
17-
// let target_minus_x: Vec<(usize, i32)> = nums_with_index
18-
// .iter()
19-
// .map(|(index, num)| (*index, target - num))
20-
// .collect();
21-
22-
// // target - xにした配列と元の配列を比較して、一致するものを返却
23-
// for (index, num) in target_minus_x {
24-
// for (i, n) in nums_with_index.iter() {
25-
// if num == *n && index != *i {
26-
// return vec![index as i32, *i as i32];
27-
// }
28-
// }
29-
// }
30-
31-
return vec![];
8+
for (i, num) in nums.iter().enumerate() {
9+
// ターゲットから数値を引いた値がハッシュマップに存在するか
10+
let diff = target - num;
11+
if let Some(&index) = hash_map.get(&diff) {
12+
return vec![index, i as i32];
13+
}
14+
// 存在しない場合はハッシュマップに数値とインデックスを追加
15+
hash_map.insert(num.clone(), i as i32);
16+
}
17+
vec![]
3218
}
3319
}
3420

3521
#[cfg(test)]
3622
mod tests {
3723
use super::*;
3824
#[test]
39-
fn test_two_sum() {
25+
fn test_two_sum_1() {
4026
let nums = vec![2, 7, 11, 15];
4127
let target = 9;
4228
let result = Solution::two_sum(nums, target);
4329
assert_eq!(result, vec![0, 1]);
4430
}
31+
32+
#[test]
33+
fn test_two_sum_2() {
34+
let nums = vec![3, 2, 4];
35+
let target = 6;
36+
let result = Solution::two_sum(nums, target);
37+
assert_eq!(result, vec![1, 2]);
38+
}
39+
40+
#[test]
41+
fn test_two_sum_3() {
42+
let nums = vec![3, 3];
43+
let target = 6;
44+
let result = Solution::two_sum(nums, target);
45+
assert_eq!(result, vec![0, 1]);
46+
}
47+
48+
#[test]
49+
fn test_two_sum_4() {
50+
let nums = vec![0, 4, 3, 0];
51+
let target = 0;
52+
let result = Solution::two_sum(nums, target);
53+
assert_eq!(result, vec![0, 3]);
54+
}
4555
}

0 commit comments

Comments
 (0)