From 6aaba6fdf96baac08a82f59788f1545cf812e792 Mon Sep 17 00:00:00 2001 From: simonhancrew <597494370@qq.com> Date: Wed, 12 May 2021 17:53:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C=20Python3=20Rust=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 6c9d99dd..21f798a9 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -106,6 +106,18 @@ public int[] twoSum(int[] nums, int target) { Python: +```python3 +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + hashmap={} + for ind,num in enumerate(nums): + hashmap[num] = ind + for i,num in enumerate(nums): + j = hashmap.get(target - num) + if j is not None and i!=j: + return [i,j] +``` + Go: @@ -122,6 +134,28 @@ func twoSum(nums []int, target int) []int { } ``` +Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut map = HashMap::with_capacity(nums.len()); + + for i in 0..nums.len() { + if let Some(k) = map.get(&(target - nums[i])) { + if *k != i { + return vec![*k as i32, i as i32]; + } + } + map.insert(nums[i], i); + } + panic!("not found") + } +} +``` +