题目描述
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。
Input Param
n 输入随机数的个数
inputArray n个随机整数组成的数组
Return Value
OutputArray 输出处理后的随机整数
注:测试用例保证输入参数的正确性,答题者无需验证。测试用例不止一组。
输入描述:
输入多行,先输入随机整数的个数,再输入相应个数的整数
输出描述:
返回多行,处理后的结果
输入例子:
11 10 20 40 32 67 40 20 89 300 400 15
输出例子:
10 15 20 32 40 67 89 300 400
<span style="font-size:18px;">import java.util.*;
public class suijiNum {
static void RanNum(int count,int[] nums)
{
//利用HashSet不可插入重复值除掉输入的重复数据
HashSet hs=new HashSet();
for(int i=0;i<count;i++)
{
hs.add(nums[i]);//将数据输入到HashSet
}
//定义一个数组保存去重之后的数据
int count1=hs.size();//记录去重后的数据个数
int[] nums1=new int[count1];
Iterator it=hs.iterator();
while(it.hasNext())
{
for(int i=0;i<count1;i++)
{
nums1[i]=(int)it.next();
}
}
Sort(nums1);
}
//对去重后的数据进行排序
static void Sort(int[] arr)
{
for(int i=1;i<arr.length;i++)
{
int insertVal=arr[i];
//inserVal准备和前一个数相比较
int index=i-1;
while(index>=0 && insertVal<arr[index])
{
//将arr[index]向后移一位
arr[index+1]=arr[index];
//让index向前移
index--;
}
//将inserVal插入到适当位置
arr[index+1]=insertVal;
}
for(int j=0;j<arr.length;j++)
{
System.out.print(arr[j]+" ");
}
}
public static void main(String[] args) {
//获取键盘输入的数据
Scanner s=new Scanner(System.in);
int count=s.nextInt();
int[] nums=new int[count];
for(int i=0;i<count;i++)
{
nums[i]=s.nextInt();
}
RanNum(count,nums);
}
}</span>
<span style="font-size:18px;">import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt())
{
int num = scan.nextInt();
TreeSet<Integer> tSet = new TreeSet<Integer>();
while (num != 0)
{
tSet.add(scan.nextInt());
num--;
}
Iterator<Integer> it = tSet.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}
}
}</span>
TreeSet详解:
http://blog.csdn.net/tingzhiyi/article/details/52160993