Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to find K most frequent elements in an unsorted array with VB.NET

1 Answer

0 votes
Imports System
Imports System.Linq
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub PrintKMostFrequentNumbers(ByVal arr As Integer(), ByVal K As Integer)
        Dim dic As IDictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)()
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 1
            If dic.ContainsKey(arr(i)) Then
                dic(arr(i)) += 1
            Else
                dic(arr(i)) = 1
            End If
        Next

        Dim list As List(Of KeyValuePair(Of Integer, Integer)) = dic.ToList()
	
        list.Sort(Function(pair1, pair2) pair1.Value.CompareTo(pair2.Value))

        For Each element In list
            Console.WriteLine(element)
        Next

        Dim list_size As Integer = list.Count

	For i As Integer = list_size - 1 To list_size - K - 1 + 1 step -1
            Console.Write(list.ElementAt(i).Key & " ")
        Next
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {4, 5, 19, 50, 7, 19, 8, 19, 3, 3, 6, 3, 27, 19, 3, 3}
        Dim K As Integer = 2

        PrintKMostFrequentNumbers(arr, K)
    End Sub
End Class





' run:
'
' [4, 1]
' [5, 1]
' [50, 1]
' [7, 1]
' [8, 1]
' [6, 1]
' [27, 1]
' [19, 4]
' [3, 5]
' 3 19
' 

 



answered Apr 29, 2023 by avibootz

Related questions

...