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 result = 0; 10 int max = 0; 11 int leader = 0; 12 int leftLeader = 0; 13 int rightLeader = 0; 14 15 int[] arrLeftLeader = new int[A.Length]; 16 int[] arrRightLeader = new int[A.Length]; 17 Dictionary<int, int> dic = new Dictionary<int, int>(); 18 19 for (int i = 0; i < A.Length; i++) 20 { 21 if (!dic.ContainsKey(A[i])) 22 dic.Add(A[i], 1); 23 else 24 dic[A[i]]++; 25 26 if (dic[A[i]] > max) 27 { 28 max = dic[A[i]]; 29 leader = A[i]; 30 } 31 if (max > (i + 1) / 2) 32 arrLeftLeader[i] = leader; 33 else 34 arrLeftLeader[i] = -1; 35 } 36 37 max = 0; 38 dic.Clear(); 39 40 for (int i = A.Length - 1; i >= 0; i--) 41 { 42 if (!dic.ContainsKey(A[i])) 43 dic.Add(A[i], 1); 44 else 45 dic[A[i]]++; 46 47 if (dic[A[i]] > max) 48 { 49 max = dic[A[i]]; 50 leader = A[i]; 51 } 52 if (max > (A.Length - i) / 2) 53 arrRightLeader[i] = leader; 54 else 55 arrRightLeader[i] = -1; 56 } 57 58 for (int i = 0; i < A.Length - 1; i++) 59 { 60 leftLeader = arrLeftLeader[i]; 61 rightLeader = arrRightLeader[i + 1]; 62 if (leftLeader != -1 && rightLeader != -1 && leftLeader == rightLeader) 63 result++; 64 } 65 66 return result; 67 }
时间: 2024-10-12 02:13:46