128. 最长连续序列

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func longestConsecutive(nums []int) int {
  7. if len(nums)==0{
  8. return 0
  9. }
  10. sort.Ints(nums)
  11. count :=1
  12. max := count
  13. for i:=1;i<len(nums);i++{
  14. if nums[i]==nums[i-1]{
  15. continue
  16. }
  17. if nums[i-1]+1==nums[i]{
  18. count++
  19. }else {
  20. if max<count{
  21. max = count
  22. }
  23. count=1
  24. }
  25. }
  26. if max<count{
  27. max = count
  28. }
  29. return max
  30. }
  31. func main() {
  32. fmt.Println(longestConsecutive([]int{100, 4, 200, 1, 3, 2}))
  33. fmt.Println(longestConsecutive([]int{0,-1}))
  34. fmt.Println(longestConsecutive([]int{1,2,0,1}))
  35. }