Created
April 21, 2019 09:04
-
-
Save joeke80215/fefc0ae28f4bd5a6c246aebc9133aa40 to your computer and use it in GitHub Desktop.
Golang 最常連續數組
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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