最长连续序列
This commit is contained in:
42
Hash/zuichanglianxuxulie/main.go
Normal file
42
Hash/zuichanglianxuxulie/main.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println(longestConsecutive([]int{0}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func longestConsecutive(nums []int) int {
|
||||||
|
exist := make(map[int]struct{})
|
||||||
|
hash := make(map[int]int)
|
||||||
|
maxresult := 0
|
||||||
|
sort.Slice(nums, func(i, j int) bool {
|
||||||
|
return nums[i] < nums[j]
|
||||||
|
})
|
||||||
|
for i := 0; i < len(nums); i++ {
|
||||||
|
exist[nums[i]] = struct{}{}
|
||||||
|
}
|
||||||
|
for i := 0; i < len(nums); i++ {
|
||||||
|
j := nums[i]
|
||||||
|
v := 0
|
||||||
|
for {
|
||||||
|
j++
|
||||||
|
if _, ok := exist[j]; ok {
|
||||||
|
v += 1
|
||||||
|
if _, okk := exist[j+1]; okk {
|
||||||
|
delete(exist, j)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hash[nums[i]] = v + 1
|
||||||
|
if v >= maxresult {
|
||||||
|
maxresult = v + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return maxresult
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user