Update 0001.两数之和.md

This commit is contained in:
buptz2b
2025-02-04 22:00:18 +08:00
committed by GitHub
parent 861c770ae2
commit 3b2373d35f

View File

@ -287,17 +287,16 @@ func twoSum(nums []int, target int) []int {
``` ```
```go ```go
// 使用map方式解题降低时间复杂度
func twoSum(nums []int, target int) []int { func twoSum(nums []int, target int) []int {
m := make(map[int]int) m := make(map[int]int)
for index, val := range nums { for i, num := range nums {
if preIndex, ok := m[target-val]; ok { complement := target - num
return []int{preIndex, index} if index, found := m[complement]; found {
} else { return []int{index, i}
m[val] = index
} }
m[num] = i
} }
return []int{} return nil // 返回空数组 nil 代替空切片
} }
``` ```