Created
July 29, 2016 18:15
-
-
Save jianminchen/1941a6b82525feefe15a2c477e0a0a0b to your computer and use it in GitHub Desktop.
K most frequent numbers in array - C# practice - using LINQ - workable solution - underneath LINQ OrderByDescending time complexity - ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace KMostFrequentNumberInArray | |
{ | |
/* | |
* Find k most frequent numbers in the array | |
Problem: | |
// nums = [5, 3, 1, 1, 1, 3, 73, 1] | |
// k = 1 | |
// return [1] | |
// k = 2 | |
// return [1, 3] | |
// k = 3 | |
// return [1, 3, 5] | |
First, go through the array once, and keep the count for every distinct value: | |
We can use LINK to call order by and then get Top k values. | |
*/ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
int[] nums = new int[] { 5, 3, 1, 1, 1, 3, 73, 1 }; | |
IList<int> test1 = kMostFrequentNumberInArray(nums, 1); | |
IList<int> test2 = kMostFrequentNumberInArray(nums, 2); | |
IList<int> test3 = kMostFrequentNumberInArray(nums, 3); | |
} | |
/* | |
* K most frequent numbers in the array | |
* Go through the array once to record the count of each distinct number; | |
* And then, use LINQ calls to get top k most frequent number | |
*/ | |
public static IList<int> kMostFrequentNumberInArray(int[] arr, int k) | |
{ | |
IList<int> res = new List<int>(); | |
if (arr == null || arr.Length == 0) | |
return res; | |
Dictionary<int, int> numberCounts = new Dictionary<int, int>(); | |
for (int i = 0; i < arr.Length; i++) | |
{ | |
int tmp = arr[i]; | |
if (numberCounts.ContainsKey(tmp)) | |
{ | |
numberCounts[tmp] += 1; | |
} | |
else | |
{ | |
numberCounts.Add(tmp, 1); | |
} | |
} | |
var selected = numberCounts.OrderByDescending(x => x.Value).Take(k); | |
foreach(var item in selected) | |
{ | |
res.Add(item.Key); | |
} | |
return res; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment