黑马程序员技术交流社区
标题:
有一个10个数的数组,计算其中不重复数字的个数。
[打印本页]
作者:
hunter
时间:
2013-4-3 20:41
标题:
有一个10个数的数组,计算其中不重复数字的个数。
比如一个数组。
作者:
guobin_lu
时间:
2013-4-3 20:42
int[] values = { 1, 3, 9, 99, 97, 5, 3 };
HashSet<int> set = new HashSet<int>();
foreach (int i in values)
{
set.Add(i);
}
foreach (int i in set)
{
Console.WriteLine(i);
}
复制代码
HashSet用于盛放不同的数据,相同的数据只保留一份
作者:
曾玉锋
时间:
2013-4-3 21:08
int[] arr = { 1,3,8,12,3,4,21};
int count = 0;
Dictionary<int, int> dic = new Dictionary<int, int>();
//先将元素和出现的次数 放入一个集合中
foreach(int item in arr)
{
if (dic.ContainsKey(item))
{
dic[item] += 1;
}
else {
dic[item] = 1;
}
}
//对集合遍历,如果元素只出现一次,则加1,否则忽略
foreach(KeyValuePair<int,int> kv in dic)
{
if(kv.Value==1)
{
count++;
}
}
Console.WriteLine(count);
Console.ReadKey();
复制代码
重复的数就不算么?如果是这个意思,下面是我的答案,如果重复的数也算一个,那前面的同学已经给出了答案
作者:
DWC_5101
时间:
2013-4-3 21:10
下面方法也可以实现:
int[] arr = new int[] { 1, 1, 3, 4, 3, 2 };
List<int> list = arr.ToList(); //将数组转成list
IEnumerable<int> result = list.Distinct(); //将list中重复项删除
Console.WriteLine(result.Count().ToString()); //输出list中元素个数,即为数组中不同元素个数
作者:
冯超
时间:
2013-4-3 21:11
import java.util.Arrays;
public class test11 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {1,2,3,4,5,6};
int n = 0;
for(int i =0; i < a.length; i++) {
int temp = a[i];
boolean tag = true;
for(int j = i + 1; j < a.length; j++) {
if(temp == a[j]) {
tag = false;
}
}
if(tag)
n++;
}
System.out.println(n);
}
}
复制代码
纯粹是小算法!
作者:
_王涛
时间:
2013-4-3 21:20
本帖最后由 _王涛 于 2013-4-3 22:53 编辑
给你举个简单例子吧:
public class StringDemo {
public static void main(String[] args) {
int[] arr3={12,7,1,12,8,12,7,9,10,2};
int count1=0;
int count2=0;
for(int i=0;i<arr3.length;i++)
{
for(int j=0;j<arr3.length;j++)
{
if(arr3[i]==arr3[j])
{
count1++;
}
}
if(count1==1)
{
count2++;
}
count1=0;
}
System.out.println(count2);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2