如何判断一个数组中相同数的个数?比如int[]nums=new int[5]{1,1,3,1,3}.1有三个,3有两个,C#该怎么判断呢
3个回答
展开全部
int[] a = new int[] { 1,1,2,4,6,6,3,1};
Hashtable ht = new Hashtable();
for (int i = 0; i < a.Length; i++)
{
int b = a[i];
int count = 0;
int flag = 0;
#region 判断哈希表中已经存在该值,如果已存在,不再进行比较
if (ht.Count > 0)
{
foreach (System.Collections.DictionaryEntry de in ht)
{
if (de.Key.ToString() == a[i].ToString())
{
flag = 1;
break;
}
}
if (flag == 1)
{
continue;
}
}
#endregion
#region 比较,和b相同的值有几个,写入哈希表
for (int j = 0; j < a.Length; j++)
{
if (i != j)
{
if (b == a[j])
{
count++;
}
}
}
ht.Add(b.ToString(), count.ToString());
#endregion
}
#region 输出结果
string result = "结果:<br/>";
foreach (System.Collections.DictionaryEntry de in ht)
{
result += de.Key.ToString() + "有" + de.Value.ToString() + "个相同<br/>";
}
#endregion
Response.Write(result);
结果:
4有0个相同
6有1个相同
1有2个相同
2有0个相同
3有0个相同
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
写的不是很好,希望对你有所帮助
int[] nNumlist = new int[] { 1, 2, 3, 4, 1, 1, 1, 2, 3, 4 };
Array.Sort(nNumlist);
int nTemp = nNumlist[0];
int nCount = 0;
for (int i = 0; i < nNumlist.Length; i++)
{
if (nTemp != nNumlist[i])
{
Console.WriteLine("Count of Number {0} is {1}", nTemp, nCount);
nTemp = nNumlist[i];
nCount = 1;
}
else
{
nCount++;
}
if (i == nNumlist.Length - 1)
{
Console.WriteLine("Count of Number {0} is {1}", nNumlist[i], nCount);
}
}
int[] nNumlist = new int[] { 1, 2, 3, 4, 1, 1, 1, 2, 3, 4 };
Array.Sort(nNumlist);
int nTemp = nNumlist[0];
int nCount = 0;
for (int i = 0; i < nNumlist.Length; i++)
{
if (nTemp != nNumlist[i])
{
Console.WriteLine("Count of Number {0} is {1}", nTemp, nCount);
nTemp = nNumlist[i];
nCount = 1;
}
else
{
nCount++;
}
if (i == nNumlist.Length - 1)
{
Console.WriteLine("Count of Number {0} is {1}", nNumlist[i], nCount);
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询