public static int degreeOfArray(List<int> arr)
{
int count = arr.Count;
int[] freQue = new int[count];
//Dictionary<int,int> freQue=new Dictionary<int , int> ();
for (int i = 0; i < count; i++)
{
//freQue.Add(i, 0);
freQue[i] = 0;
for (int j = 0; j < count; j++)
{
if ( arr[i] == arr[j])
{
freQue[i]++;
}
}
}
int max = 0;
int index = 0;
//foreach(int m in freQue)
for (int k = 0; k < freQue.Count(); k++)
{
if (freQue[k] > max)
{
max = freQue[k];
index = k;
}
}
int rightIndex = 0;
for (int x = count - 1; x >= 0; x--)
{
if (arr[x] == arr[index])
{
rightIndex = x;
}
}
return rightIndex - index + 1;
}
Dictionary<int, int> frequency = new Dictionary<int, int>(); // 记录每个元素的出现次数
Dictionary<int, int> firstIndex = new Dictionary<int, int>(); // 记录每个元素第一次出现的索引
Dictionary<int, int> lastIndex = new Dictionary<int, int>(); // 记录每个元素最后一次出现的索引
int maxFrequency = 0; // 最大出现次数
foreach (int num in nums)
{ if (!firstIndex.ContainsKey(num)) firstIndex[num] = Array.IndexOf(nums, num); // 记录第一次出现的索引
lastIndex[num] = Array.LastIndexOf(nums, num); // 记录最后一次出现的索引
frequency[num] = frequency.ContainsKey(num) ? frequency[num] + 1 : 1; // 更新出现次数
maxFrequency = Math.Max(maxFrequency, frequency[num]); // 更新最大出现次数
}
int minLength = nums.Length; // 最短子数组长度
foreach (var pair in frequency)
{
if (pair.Value == maxFrequency)
{ minLength = Math.Min(minLength, lastIndex[pair.Key] - firstIndex[pair.Key] + 1); // 计算最短子数组长度
}
}
return minLength;
}
}
public class Program
{
public static void Main(string[] args)
{
int[] nums = { 1, 2, 2, 3, 1, 4, 2 };
ArrayDegree arrayDegree = new ArrayDegree();
int minLength = arrayDegree.FindShortestSubarrayLength(nums);
Console.WriteLine("数组的度数为:" + minLength);
}
}
标签:arr,Dictionary,int,freQue,num,frequency,数组,长度 From: https://www.cnblogs.com/Dongmy/p/18092823