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;
|
|
|
|
struct SolutionBruteForce;
|
|
|
|
struct SolutionHashMap;
|
|
|
|
|
2023-02-03 18:53:15 +08:00
|
|
|
/* 方法一:暴力枚举 */
|
2023-01-14 21:45:52 +08:00
|
|
|
impl SolutionBruteForce {
|
|
|
|
pub fn two_sum(nums: &Vec<i32>, target: i32) -> Vec<i32> {
|
2023-02-05 16:25:42 +08:00
|
|
|
let size = nums.len();
|
|
|
|
// 两层循环,时间复杂度 O(n^2)
|
|
|
|
for i in 0..size - 1 {
|
|
|
|
for j in i + 1..size {
|
2023-01-14 21:45:52 +08:00
|
|
|
if nums[i] + nums[j] == target {
|
|
|
|
return vec![i as i32, j as i32];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-03 18:53:15 +08:00
|
|
|
/* 方法二:辅助哈希表 */
|
2023-01-14 21:45:52 +08:00
|
|
|
impl SolutionHashMap {
|
|
|
|
pub fn two_sum(nums: &Vec<i32>, target: i32) -> Vec<i32> {
|
2023-02-05 16:25:42 +08:00
|
|
|
// 辅助哈希表,空间复杂度 O(n)
|
|
|
|
let mut dic = HashMap::new();
|
|
|
|
// 单层循环,时间复杂度 O(n)
|
|
|
|
for (i, num) in nums.iter().enumerate() {
|
|
|
|
match dic.get(&(target - num)) {
|
2023-01-14 21:45:52 +08:00
|
|
|
Some(v) => return vec![*v as i32, i as i32],
|
2023-02-05 16:25:42 +08:00
|
|
|
None => dic.insert(num, i as i32)
|
2023-01-14 21:45:52 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-05 16:25:42 +08:00
|
|
|
/* Driver Code */
|
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-01-15 01:25:18 +08:00
|
|
|
// 方法一
|
2023-01-14 21:45:52 +08:00
|
|
|
let res = SolutionBruteForce::two_sum(&nums, target);
|
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-01-14 21:45:52 +08:00
|
|
|
let res = SolutionHashMap::two_sum(&nums, target);
|
2023-02-05 16:25:42 +08:00
|
|
|
print!("\n方法二 res = ");
|
2023-02-09 00:25:01 +08:00
|
|
|
print_util::print_array(&res);
|
|
|
|
}
|