2023-02-09 00:25:01 +08:00
|
|
|
/*
|
2023-01-14 21:45:52 +08:00
|
|
|
* File: leetcode_two_sum.rs
|
|
|
|
* Created Time: 2023-01-14
|
2023-02-05 16:25:42 +08:00
|
|
|
* Author: xBLACICEx (xBLACKICEx@outlook.com), sjinzh (sjinzh@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();
|
|
|
|
// 两层循环,时间复杂度 O(n^2)
|
|
|
|
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>> {
|
|
|
|
// 辅助哈希表,空间复杂度 O(n)
|
|
|
|
let mut dic = HashMap::new();
|
|
|
|
// 单层循环,时间复杂度 O(n)
|
|
|
|
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-01-14 21:45:52 +08:00
|
|
|
let target = 9;
|
|
|
|
|
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);
|
|
|
|
}
|