How to find the length of the longest consecutive sequence of an unsorted list of integers in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class LongestConsecutiveSequence
    Public Shared Function LongestConsecutive(ByVal nums As List(Of Integer)) As Integer
        Dim numSet As HashSet(Of Integer) = New HashSet(Of Integer)(nums)
        Dim longestStreak As Integer = 0

        For Each num As Integer In numSet

            If Not numSet.Contains(num - 1) Then
                Dim currentNum As Integer = num
                Dim currentStreak As Integer = 1

                While numSet.Contains(currentNum + 1)
                    currentNum += 1
                    currentStreak += 1
                End While

                longestStreak = Math.Max(longestStreak, currentStreak)
            End If
        Next

        Return longestStreak
    End Function

    Public Shared Sub Main()
        Dim nums As List(Of Integer) = New List(Of Integer) From {
            680,
            4,
            590,
            3,
            2,
            1
        }
        Dim result As Integer = LongestConsecutive(nums)
	
        Console.WriteLine("Length of the longest consecutive sequence: " & result)
    End Sub
End Class




' run:
'
' Length of the longest consecutive sequence: 4
'

 



answered Aug 18 by avibootz
...