From 4980496c05aad48ea28cc0ed471cc08ffe36b9d6 Mon Sep 17 00:00:00 2001 From: Camille0512 Date: Fri, 25 Feb 2022 18:59:56 +0800 Subject: [PATCH] 0001. Add python v2. Making use of the dictionary property. --- problems/0001.两数之和.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 22b2e7eb..9571a773 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -118,6 +118,18 @@ class Solution: return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引 ``` +Python (v2): + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + rec = {} + for i in range(len(nums)): + rest = target - nums[i] + # Use get to get the index of the data, making use of one of the dictionary properties. + if rec.get(rest, None) is not None: return [rec[rest], i] + rec[nums[i]] = i +``` Go: