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;
        }
    }

 

posted on 2018-09-30 18:46  Sempron2800+  阅读(98)  评论(0编辑  收藏  举报