mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-05 06:36:41 +08:00
@ -285,17 +285,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 代替空切片
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user