leet-code/longest-consecutive-sequence/sol.go

30 lines
434 B
Go

package main
func longestConsecutive(nums []int) (max int) {
exists := make(map[int]bool, len(nums))
for _, n := range nums {
exists[n] = true
}
for _, n := range nums {
if _, ok := exists[n]; ok {
exists[n] = false
l := 1
for exists[n+1] {
l++
n++
exists[n] = false
}
n -= l - 1
for exists[n-1] {
l++
n--
exists[n] = false
}
if l > max {
max = l
}
}
}
return max
}