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") + } +} +``` +