347. Top K Frequent Elements

This commit is contained in:
Пытков Роман
2024-02-07 23:27:37 +03:00
parent c47d2185b5
commit 9b3c8c3fef
5 changed files with 60 additions and 4 deletions

View File

@@ -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>

View 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)));

View 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();
}
}