From 175f1c5e1a459e72511ae56ce33828a8fc367690 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Mon, 16 Aug 2021 19:11:16 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96=200001.=E4=B8=A4=E6=95=B0?= =?UTF-8?q?=E4=B9=8B=E5=92=8C.md=20python=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原代码过于赘余,需要遍历两次且可读性较差。更新后的代码在维持题主题意的基础上的一次优化 --- problems/0001.两数之和.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index f8c9da5f..9b961d0b 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -110,13 +110,14 @@ Python: ```python 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] + records = dict() + + # 用枚举更方便,就不需要通过索引再去取当前位置的值 + for idx, val in enumerate(nums): + if target - val not in records: + records[val] = idx + else: + return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引 ```