347. Top K Frequent Elements
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>_347._Top_K_Frequent_Elements</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
4
347. Top K Frequent Elements/Program.cs
Normal file
4
347. Top K Frequent Elements/Program.cs
Normal file
@@ -0,0 +1,4 @@
|
||||
using _347._Top_K_Frequent_Elements;
|
||||
|
||||
var sol = new Solution();
|
||||
Console.WriteLine(string.Join(", ", sol.TopKFrequent([1,1,1,2,2,3], 2)));
|
||||
13
347. Top K Frequent Elements/Solution.cs
Normal file
13
347. Top K Frequent Elements/Solution.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace _347._Top_K_Frequent_Elements;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public int[] TopKFrequent(int[] nums, int k)
|
||||
{
|
||||
var dictionary = new Dictionary<int, int>();
|
||||
foreach (var num in nums)
|
||||
if (!dictionary.TryAdd(num, 1))
|
||||
dictionary[num]++;
|
||||
return dictionary.OrderByDescending(kp=>kp.Value).Take(k).Select(kp=>kp.Key).ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user