From 3b2373d35f1f551826b473d019fa1f1e58966f79 Mon Sep 17 00:00:00 2001 From: buptz2b <155848478+buptz2b@users.noreply.github.com> Date: Tue, 4 Feb 2025 22:00:18 +0800 Subject: [PATCH] =?UTF-8?q?Update=200001.=E4=B8=A4=E6=95=B0=E4=B9=8B?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index e982ae12..3c92e4df 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -287,17 +287,16 @@ func twoSum(nums []int, target int) []int { ``` ```go -// 使用map方式解题,降低时间复杂度 func twoSum(nums []int, target int) []int { m := make(map[int]int) - for index, val := range nums { - if preIndex, ok := m[target-val]; ok { - return []int{preIndex, index} - } else { - m[val] = index + for i, num := range nums { + complement := target - num + if index, found := m[complement]; found { + return []int{index, i} } + m[num] = i } - return []int{} + return nil // 返回空数组 nil 代替空切片 } ```