Input : {5, 13, 6, 5, 13, 7, 8, 6, 5}
Output : {5, 5, 5, 13, 13, 6, 6, 7, 8}
The question is to arrange the numbers in the array in
C#. It takes the most obvious approach: sort by frequency and ordinal.
Output: 5 5 5 13 13 6 6 7 8
.
Space: O(n). Time: O(n log n).
class Program
{
class FreqAndOrdinal
{
public int Frequency;
public int Ordinal;
public FreqAndOrdinal(int freq, int ord)
{
this.Frequency = freq;
this.Ordinal = ord;
}
}
static int Compare(FreqAndOrdinal x, FreqAndOrdinal y)
{
int result = y.Frequency.CompareTo(x.Frequency);
return result == 0 ? x.Ordinal.CompareTo(y.Ordinal) : result;
}
static void Main(string[] args)
{
int[] nums = new int[] { 5, 13, 6, 5, 13, 7, 8, 6, 5 };
var freqLookup = new Dictionary<int, FreqAndOrdinal>(nums.Length);
for (int i = 0; i < nums.Length; i++)
{
FreqAndOrdinal tmp;
if (freqLookup.TryGetValue(nums[i], out tmp))
++tmp.Frequency;
else
freqLookup[nums[i]] = new FreqAndOrdinal(1, i);
}
Array.Sort(nums, (x,y) => Compare(freqLookup[x], freqLookup[y]));
for (int i = 0; i < nums.Length; i++)
{
Console.Write(" {0}", nums[i]);
}
Console.ReadKey();
}
}