-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
39 lines (37 loc) · 1.14 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
using System.Linq;
namespace SortArrayByIncreasingFrequency
{
class Program
{
static void Main(string[] args)
{
int[] nums = {1, 1, 2, 2, 2, 3};
Console.WriteLine(FrequencySort_Linq(nums));
}
static int[] FrequencySort_Linq(int[] nums)
{
var dict = new Dictionary<int, int>();
foreach (var num in nums)
{
if (!dict.ContainsKey(num))
dict[num] = 0;
dict[num]++;
}
dict = dict.OrderBy(x => x.Value).ThenByDescending(x => x.Key).ToDictionary(k => k.Key, v => v.Value);
var res = new int[nums.Length];
int index = 0;
foreach (var kv in dict)
{
for (int i = 0; i < kv.Value; i++)
res[index++] = kv.Key;
}
return res;
}
public int[] FrequencySort(int[] nums)
{
return nums.GroupBy(x => x).OrderBy(x => x.Count()).ThenByDescending(x => x.Key).SelectMany(x => x).ToArray();
}
}
}