class Program
{
static void Main(string[] args)
{
int[] input = { 1, 1, 1, 2, 2, 5, 2, 4, 9, 9, 20 };
IDuplicationFinder dup1 = new Duplication1();
string str1 = dup1.FindDuplication(input, 3);
Console.WriteLine(str1); IDuplicationFinder dup2 = new Duplication2();
string str2 = dup2.FindDuplication(input, 3);
Console.WriteLine(str2);
Console.Read();
}
}
class Duplication1 : IDuplicationFinder
{
public string FindDuplication(int[] input, uint minTimes)
{
Dictionary<int, int> valuedic = new Dictionary<int, int>();
#region 整个完全遍历
//foreach (var v in input)
//{
// var numtimes = input.Where(m => m == v).Count();
// if (numtimes >= minTimes && !valuedic.Keys.Contains(v))
// valuedic.Add(v, numtimes);
//}
#endregion
#region linq group
var groupnum = input.GroupBy(m => m);
foreach (var g in groupnum)
{
if (g.Count() >= minTimes)
valuedic.Add(g.Key, g.Count());
}
#endregion
return GetValue(valuedic);
}
private static string GetValue(Dictionary<int, int> valuedic)
{
StringBuilder sb = new StringBuilder();
foreach (var d in valuedic)
{
sb.AppendFormat("{0}出现了{1}次", d.Key, d.Value);
sb.AppendLine();
}
return sb.ToString();
} }
class Duplication2 : IDuplicationFinder
{
public string FindDuplication(int[] input, uint minTimes)
{
List<int> result = new List<int>();
Array.Sort(input);
if (minTimes == 1)//如果次数是1,就要把去重显示
{
if (input[0] == input[1])
result.Add(input[1]);
for (int i = 1; i < input.Length - 1; i++)
{
if (input[i] != input[i + 1])
result.Add(input[i + 1]);
}
}
else
{
int count = 1;//排序后 前一个跟后一个对比,所以从1开始
for (int i = 0; i < input.Length - 1; i++)
{
if (result.Count > 0 && result.Last() == input[i])
continue;
if (input[i] == input[i + 1])
{
count++;
if (count >= minTimes)
{
result.Add(input[i]);
count = 1;
}
} }
} return string.Join(",", result);
}
}
interface IDuplicationFinder
{
string FindDuplication(int[] input, uint minTimes);
}
t=[1,22,33,1,44,22,11,3,224,5,6,22,1,44]//查找出现次数最多的数字和次数 ruby
hst={}
t.each do |item|
if(hst.key?(item))
hst[item]+=1
else
hst[item]=1
end
end
p hst
b = Hash[hst.sort_by(){ |k, v| v }.reverse]
p b
p b.first