mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-13 23:40:35 +08:00
Update 0167、0169
This commit is contained in:
@ -6,11 +6,12 @@ func majorityElement(nums []int) int {
|
||||
for i := 0; i < len(nums); i++ {
|
||||
if count == 0 {
|
||||
res, count = nums[i], 1
|
||||
}
|
||||
if nums[i] == res {
|
||||
count++
|
||||
} else {
|
||||
count--
|
||||
if nums[i] == res {
|
||||
count++
|
||||
} else {
|
||||
count--
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
|
@ -43,13 +43,14 @@ func twoSum167(numbers []int, target int) []int {
|
||||
for i < j {
|
||||
if numbers[i]+numbers[j] == target {
|
||||
return []int{i + 1, j + 1}
|
||||
} else if numbers[i]+numbers[j] < target {
|
||||
}
|
||||
if numbers[i]+numbers[j] < target {
|
||||
i++
|
||||
} else {
|
||||
j--
|
||||
}
|
||||
}
|
||||
return []int{-1, -1}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 解法二 不管数组是否有序,空间复杂度比上一种解法要多 O(n)
|
||||
@ -57,8 +58,8 @@ func twoSum167_1(numbers []int, target int) []int {
|
||||
m := make(map[int]int)
|
||||
for i := 0; i < len(numbers); i++ {
|
||||
another := target - numbers[i]
|
||||
if _, ok := m[another]; ok {
|
||||
return []int{m[another] + 1, i + 1}
|
||||
if idx, ok := m[another]; ok {
|
||||
return []int{idx + 1, i + 1}
|
||||
}
|
||||
m[numbers[i]] = i
|
||||
}
|
||||
|
@ -63,6 +63,7 @@ func majorityElement1(nums []int) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user