2023-02-09 00:25:01 +08:00
|
|
|
/*
|
2023-05-09 00:36:18 +08:00
|
|
|
* File: two_sum.rs
|
2023-01-14 21:45:52 +08:00
|
|
|
* Created Time: 2023-01-14
|
2024-01-02 01:25:37 +08:00
|
|
|
* Author: xBLACICEx (xBLACKICEx@outlook.com), codingonion (coderonion@gmail.com)
|
2023-02-09 00:25:01 +08:00
|
|
|
*/
|
|
|
|
|
|
|
|
include!("../include/include.rs");
|
2023-01-14 21:45:52 +08:00
|
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
2023-02-03 18:53:15 +08:00
|
|
|
/* 方法一:暴力枚举 */
|
2023-02-09 23:07:43 +08:00
|
|
|
pub fn two_sum_brute_force(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
|
|
|
let size = nums.len();
|
2023-12-02 06:21:34 +08:00
|
|
|
// 两层循环,时间复杂度为 O(n^2)
|
2023-02-09 23:07:43 +08:00
|
|
|
for i in 0..size - 1 {
|
|
|
|
for j in i + 1..size {
|
|
|
|
if nums[i] + nums[j] == target {
|
|
|
|
return Some(vec![i as i32, j as i32]);
|
2023-01-14 21:45:52 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-02-09 23:07:43 +08:00
|
|
|
None
|
2023-01-14 21:45:52 +08:00
|
|
|
}
|
|
|
|
|
2023-02-03 18:53:15 +08:00
|
|
|
/* 方法二:辅助哈希表 */
|
2023-02-09 23:07:43 +08:00
|
|
|
pub fn two_sum_hash_table(nums: &Vec<i32>, target: i32) -> Option<Vec<i32>> {
|
2023-12-02 06:21:34 +08:00
|
|
|
// 辅助哈希表,空间复杂度为 O(n)
|
2023-02-09 23:07:43 +08:00
|
|
|
let mut dic = HashMap::new();
|
2023-12-02 06:21:34 +08:00
|
|
|
// 单层循环,时间复杂度为 O(n)
|
2023-02-09 23:07:43 +08:00
|
|
|
for (i, num) in nums.iter().enumerate() {
|
|
|
|
match dic.get(&(target - num)) {
|
|
|
|
Some(v) => return Some(vec![*v as i32, i as i32]),
|
|
|
|
None => dic.insert(num, i as i32)
|
|
|
|
};
|
2023-01-14 21:45:52 +08:00
|
|
|
}
|
2023-02-09 23:07:43 +08:00
|
|
|
None
|
2023-01-14 21:45:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2023-01-15 01:25:18 +08:00
|
|
|
// ======= Test Case =======
|
2023-02-05 16:25:42 +08:00
|
|
|
let nums = vec![ 2, 7, 11, 15 ];
|
2023-05-09 00:36:18 +08:00
|
|
|
let target = 13;
|
2023-01-14 21:45:52 +08:00
|
|
|
|
2023-02-09 23:07:43 +08:00
|
|
|
// ====== Driver Code ======
|
2023-01-15 01:25:18 +08:00
|
|
|
// 方法一
|
2023-02-09 23:07:43 +08:00
|
|
|
let res = two_sum_brute_force(&nums, target).unwrap();
|
2023-02-05 16:25:42 +08:00
|
|
|
print!("方法一 res = ");
|
2023-02-09 00:25:01 +08:00
|
|
|
print_util::print_array(&res);
|
2023-01-15 01:25:18 +08:00
|
|
|
// 方法二
|
2023-02-09 23:07:43 +08:00
|
|
|
let res = two_sum_hash_table(&nums, target).unwrap();
|
2023-02-05 16:25:42 +08:00
|
|
|
print!("\n方法二 res = ");
|
2023-02-09 00:25:01 +08:00
|
|
|
print_util::print_array(&res);
|
|
|
|
}
|