CSharp · Console
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static int FindSpecialNumber(int[] arr)
{
int len = arr.Length;
if (len == 1)
return arr[0] == 1 ? 1 : -1;
var sortedMap = new SortedDictionary<int, int>();
for (int i = 0; i < len; i++)
{
if (!sortedMap.ContainsKey(arr[i]))
sortedMap[arr[i]] = 0;
sortedMap[arr[i]]++;
}
for (int i = sortedMap.Count - 1; i >= 0; i--)
{
var item = sortedMap.ElementAt(i);
if (item.Key == item.Value)
return item.Key;
}
return -1;
}
public static void Main()
{
Console.WriteLine("UniLecs");
// tests
Console.WriteLine(FindSpecialNumber(new int[] { 2, 2, 3, 4 }).ToString()); // 2
Console.WriteLine(FindSpecialNumber(new int[] { 1, 2, 2, 3, 3, 3 }).ToString()); // 3
Console.WriteLine(FindSpecialNumber(new int[] { 2, 2, 2, 3, 3 }).ToString()); // -1
}
}