1 /// <summary> 2 /// Solution 3 /// 通过率 100% 4 /// </summary> 5 /// <param name="A"></param> 6 /// <returns></returns> 7 public static int solution(int[] A) 8 { 9 int maxKey; 10 int maxValue; 11 12 if (A.Length == 0) 13 return -1; 14 if (A.Length == 1) 15 return 0; 16 17 Dictionary<int, int> dic = new Dictionary<int, int>(); 18 foreach (int num in A) 19 { 20 if (!dic.ContainsKey(num)) 21 dic.Add(num, 1); 22 else 23 dic[num]++; 24 } 25 26 dic = dic.OrderBy(o => o.Value).ToDictionary(o => o.Key, p => p.Value); 27 maxKey = dic.Keys.Last<int>(); 28 maxValue = dic.Values.Last<int>(); 29 30 if (maxValue > A.Length / 2) 31 { 32 for (int i = 0; i < A.Length; i++) 33 if (A[i] == maxKey) 34 return i; 35 } 36 37 return -1; 38 }
时间: 2024-10-18 08:21:27