Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created April 21, 2019 09:04
Show Gist options
  • Save joeke80215/fefc0ae28f4bd5a6c246aebc9133aa40 to your computer and use it in GitHub Desktop.
Save joeke80215/fefc0ae28f4bd5a6c246aebc9133aa40 to your computer and use it in GitHub Desktop.
Golang 最常連續數組
package main
import "fmt"
// longestSlice Longest Consecutive Sequence
func longestConsSeq(sorted []int) ([]int, int) {
max := 1
head := 0
for i := 0; i < len(sorted); i++ {
cur := 1
for {
if i+1 == len(sorted) {
break
}
if sorted[i]+1 != sorted[i+1] {
break
}
cur++
i++
if cur > max {
max = cur
head = i - max + 1
}
}
}
return sorted[head : head+max], max
}
func main() {
// output: [6 7 8] 3
fmt.Println(longestConsSeq([]int{5, 6, 6, 7, 8, 8, 9}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment