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

30 lines
434 B
Go
Raw Permalink Normal View History

2022-07-05 23:33:16 +00:00
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 {
2022-07-06 20:04:31 +00:00
if _, ok := exists[n]; ok {
exists[n] = false
2022-07-05 23:33:16 +00:00
l := 1
for exists[n+1] {
l++
n++
2022-07-06 20:04:31 +00:00
exists[n] = false
2022-07-05 23:33:16 +00:00
}
n -= l - 1
for exists[n-1] {
l++
n--
2022-07-06 20:04:31 +00:00
exists[n] = false
2022-07-05 23:33:16 +00:00
}
if l > max {
max = l
}
}
}
return max
}