33,010
社区成员
发帖
与我相关
我的任务
分享
private void button2_Click(object sender, EventArgs e)
{
int[] array = new int[] { 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 6, 6, 7, 8, 10, 11, 13, 13, 13, 13, 13, 13, 13, 13, 19, 20, 21, 24 };
int[] k;
//有序情况找众数法
k = Zhongshu1(array);
array = new int[] { 20, 21, 13, 24, 1, 13, 13, 13, 1, 2, 10, 11, 13, 13, 2, 2, 2, 3, 3, 3, 2, 6, 7, 2, 2, 2, 6, 8, 13, 13, 13, 2, 19 };
//无序情况找众数
k = ZhongshuNoSort(array);
}
//有序情况下的找众数
private int[] Zhongshu1(int[] source)
{
int currentValue = source[0];
int[] zhongshu = new int[source.Length];
int max = 1;
int count = 0;
int position = -1;
for (int i = 0; i <= source.Length; i++)
{
if (i < source.Length && source[i] == currentValue)
count++;
else
{
if (count > max)
{
//如果出现了更大的计数
max = count;
position = 0;
zhongshu[0] = source[i - 1];
}
else if (count == max)
zhongshu[++position] = source[i - 1];
if (i < source.Length)
{
currentValue = source[i];
count = 1;
}
}
}
//如果没有众数
if (max <= 1)
return null;
Array.Resize(ref zhongshu,position + 1);
return zhongshu;
}
//无序情况找众数
private int[] ZhongshuNoSort(int[] source)
{
int count;
bool flag = false;
Dictionary<int, int> myDict = new Dictionary<int, int>();
for (int i = 0; i < source.Length; i++)
{
if (myDict.TryGetValue(source[i],out count))
{
flag = true;
myDict[source[i]]++;
}
else
myDict.Add(source[i], 1);
}
//如果没有众数
if(!flag)
return null;
int max = 0;
int position = 0;
int[] zhongshu = new int[source.Length];
//遍历hash表,复杂度<= O(n)
foreach (KeyValuePair<int, int> myKey in myDict)
{
if (myKey.Value > max)
{
max = myKey.Value;
position = 0;
zhongshu[0] = myKey.Key;
}
else if (myKey.Value == max)
zhongshu[++position] = myKey.Key;
}
Array.Resize(ref zhongshu, position + 1);
return zhongshu;
}