feat: longest consecutive sequence
This commit is contained in:
86
pkg/longest_consecutive_sequence/main.go
Normal file
86
pkg/longest_consecutive_sequence/main.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package longest_consecutive_sequence
|
||||
|
||||
// type Node struct {
|
||||
// // The location of the parent node.
|
||||
// Parent *Node
|
||||
|
||||
// // The number of descendent nodes, including itself.
|
||||
// Children int
|
||||
// }
|
||||
|
||||
// func FindAncestor(n *Node) *Node {
|
||||
// ancestor := n
|
||||
|
||||
// for ancestor.Parent != nil {
|
||||
// ancestor = ancestor.Parent
|
||||
// }
|
||||
|
||||
// return ancestor
|
||||
// }
|
||||
|
||||
// func LongestConsecutive(nums []int) int {
|
||||
// nodes := map[int]*Node{}
|
||||
|
||||
// for _, num := range nums {
|
||||
// if _, exists := nodes[num]; exists {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// node := &Node{Parent: nil, Children: 1}
|
||||
|
||||
// if lower, lower_exists := nodes[num-1]; lower_exists {
|
||||
// ancestor := FindAncestor(lower)
|
||||
// ancestor.Parent = node
|
||||
// node.Children += ancestor.Children
|
||||
// }
|
||||
|
||||
// if upper, lower_exists := nodes[num+1]; lower_exists {
|
||||
// ancestor := FindAncestor(upper)
|
||||
// ancestor.Parent = node
|
||||
// node.Children += ancestor.Children
|
||||
// }
|
||||
|
||||
// nodes[num] = node
|
||||
// }
|
||||
|
||||
// maximum := 0
|
||||
|
||||
// for _, node := range nodes {
|
||||
// maximum = max(maximum, node.Children)
|
||||
// }
|
||||
|
||||
// return maximum
|
||||
// }
|
||||
|
||||
func LongestConsecutive(nums []int) int {
|
||||
items := map[int]bool{}
|
||||
|
||||
for _, num := range nums {
|
||||
items[num] = true
|
||||
}
|
||||
|
||||
maximum := 0
|
||||
|
||||
for item, unused := range items {
|
||||
if !unused {
|
||||
continue
|
||||
}
|
||||
|
||||
items[item] = false
|
||||
sequence := 1
|
||||
|
||||
for i := item - 1; items[i]; i-- {
|
||||
items[i] = false
|
||||
sequence++
|
||||
}
|
||||
|
||||
for i := item + 1; items[i]; i++ {
|
||||
items[i] = false
|
||||
sequence++
|
||||
}
|
||||
|
||||
maximum = max(maximum, sequence)
|
||||
}
|
||||
|
||||
return maximum
|
||||
}
|
||||
Reference in New Issue
Block a user