Merge pull request #34 from Simonhancrew/master

添加0001.两数之和 Python3 Rust 版本
This commit is contained in:
Carl Sun
2021-05-12 18:14:45 +08:00
committed by GitHub

View File

@ -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<i32>, target: i32) -> Vec<i32> {
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")
}
}
```