Go Program
package main
import (
"fmt"
"sort"
)
// longestConsecutive finds the length of the longest consecutive elements sequence in the array.
func longestConsecutive(nums []int) int {
if len(nums) == 0 {
return 0
}
// Remove duplicates and sort the array
numSet := make(map[int]struct{})
for _, num := range nums {
numSet[num] = struct{}{}
}
// Convert map keys to a slice and sort it
uniqueNums := make([]int, 0, len(numSet))
for num := range numSet {
uniqueNums = append(uniqueNums, num)
}
sort.Ints(uniqueNums)
longestStreak := 1
currentStreak := 1
// Iterate through the sorted array to find the longest streak
for i := 1; i < len(uniqueNums); i++ { if uniqueNums[i] == uniqueNums[i-1]+1 { currentStreak++ } else { if currentStreak > longestStreak {
longestStreak = currentStreak
}
currentStreak = 1
}
}
// Check at the end of the loop
return max(longestStreak, currentStreak)
}
// max returns the maximum of two integers.
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
nums := []int{100, 4, 200, 1, 3, 2}
result := longestConsecutive(nums)
fmt.Printf("The length of the longest consecutive sequence is: %d\n", result)
}
Program Explanation
The program consists of several components that work together to find the longest consecutive sequence of numbers in an array:
- Package Declaration: The program begins with the declaration of the
main
package, which is standard for Go programs. - Imports: The
fmt
package is imported for formatted I/O, andsort
is used to sort the unique numbers. - Function longestConsecutive: This function takes an array of integers and returns the length of the longest consecutive sequence.
- Handling Duplicates: A map is used to store unique numbers, removing duplicates efficiently.
- Sorting: The unique numbers are sorted to facilitate finding consecutive sequences.
- Finding Consecutive Sequences: A loop iterates through the sorted numbers, tracking the current streak of consecutive numbers and updating the longest streak as necessary.
- Helper Function max: This function returns the maximum of two integers and is used to ensure the longest streak is returned correctly.
- Main Function: The
main
function initializes an array of integers, calls thelongestConsecutive
function, and prints the result.
How to Run the Program
- Install Go on your machine if you haven’t already.
- Create a new file named
longest_sequence.go
. - Copy and paste the program code into the file.
- Open a terminal and navigate to the directory containing the file.
- Run the program using the command:
go run longest_sequence.go
.
Conclusion
This Go program effectively identifies the longest consecutive sequence in an array by utilizing maps for uniqueness and sorting. This approach ensures efficiency while maintaining clarity in the implementation.