From a5425b6d9b0235af37674b8956f8fba5be117fd4 Mon Sep 17 00:00:00 2001 From: xblakicex Date: Sat, 14 Jan 2023 14:45:52 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(codes/rust):=20add=20leetcode?= =?UTF-8?q?=5Ftwo=5Fsum.rs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode_two_sum.rs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 codes/rust/chapter_computational_complexity/leetcode_two_sum.rs diff --git a/codes/rust/chapter_computational_complexity/leetcode_two_sum.rs b/codes/rust/chapter_computational_complexity/leetcode_two_sum.rs new file mode 100644 index 000000000..95d264b89 --- /dev/null +++ b/codes/rust/chapter_computational_complexity/leetcode_two_sum.rs @@ -0,0 +1,47 @@ +/** + * File: leetcode_two_sum.rs + * Created Time: 2023-01-14 + * Author: xBLACICEx (xBLACKICEx@outlook.com ) +*/ + +use std::collections::HashMap; +struct SolutionBruteForce; +struct SolutionHashMap; + +impl SolutionBruteForce { + pub fn two_sum(nums: &Vec, target: i32) -> Vec { + for i in 0..nums.len() - 1 { + for j in i + 1..nums.len() { + if nums[i] + nums[j] == target { + return vec![i as i32, j as i32]; + } + } + } + vec![] + } +} + +impl SolutionHashMap { + pub fn two_sum(nums: &Vec, target: i32) -> Vec { + let mut hm = HashMap::new(); + + for (i, n) in nums.iter().enumerate() { + match hm.get(&(target - n)) { + Some(v) => return vec![*v as i32, i as i32], + None => hm.insert(n, i) + }; + } + vec![] + } +} + +fn main() { + let nums = vec![2,7,11,15]; + let target = 9; + + let res = SolutionBruteForce::two_sum(&nums, target); + println!("方法一 res = {:?}", res); + + let res = SolutionHashMap::two_sum(&nums, target); + println!("方法二 res = {:?}", res); +} \ No newline at end of file