Longest Consecutive Sequence - Leetcode
Problem statement:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example:
Input:
[100,4,200,1,3,2]
Expected output:
4
Explanation:
The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input:
[0,3,7,2,5,8,4,6,0,1]
Expected output:
9
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/longest-consecutive-sequence/
Golang Solution:
func longestConsecutive(nums []int) int {
if len(nums) == 0 || len(nums) == 1 {
return len(nums)
}
maxSoFar := 1
hashMap := make(map[int]bool)
for _, num := range nums {
hashMap[num] = true
}
for key, _ := range hashMap {
currVal := key
if _, ok := hashMap[currVal-1]; ok {
continue
}
tempMax := 0
for {
if _, ok := hashMap[currVal]; ok {
tempMax += 1
currVal = currVal + 1
} else {
break
}
}
if tempMax > maxSoFar {
maxSoFar = tempMax
}
}
return maxSoFar
}
