We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 2b0ca46 + 3b2373d commit c1f4e6fCopy full SHA for c1f4e6f
problems/0001.两数之和.md
@@ -285,17 +285,16 @@ func twoSum(nums []int, target int) []int {
285
```
286
287
```go
288
-// 使用map方式解题,降低时间复杂度
289
func twoSum(nums []int, target int) []int {
290
m := make(map[int]int)
291
- for index, val := range nums {
292
- if preIndex, ok := m[target-val]; ok {
293
- return []int{preIndex, index}
294
- } else {
295
- m[val] = index
+ for i, num := range nums {
+ complement := target - num
+ if index, found := m[complement]; found {
+ return []int{index, i}
296
}
+ m[num] = i
297
298
- return []int{}
+ return nil // 返回空数组 nil 代替空切片
299
300
301
0 commit comments