public class Solution { public int FindShortestSubArray(int[] nums) { //先找到最大频度的数字都有哪些,加入到一个集合中 var dic = new Dictionary<int, int>(); var dic2 = new Dictionary<int, List<int>>(); for (int i = 0; i < nums.Length; i++) { var num = nums[i]; if (!dic.ContainsKey(num)) { dic.Add(num, 1); dic2.Add(num, new List<int>()); } else { dic[num]++; } dic2[num].Add(i);//记录此数字的所有下标 } var list = dic.OrderByDescending(x => x.Value).ToList(); int maxFreq = list[0].Value; var list2 = dic.Where(x => x.Value == maxFreq).ToList(); //遍历集合,一次判断每个数最早出现的位置和最晚出现的位置 int min = int.MaxValue; foreach (var l in list2) { var num = l.Key; var begin = dic2[num].First(); var end = dic2[num].Last(); var dif = end - begin; if (min > dif) { min = dif; } } //寻找最小间隔 return min + 1; } }