华为OJ——明明的随机数

题目描述

明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了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>

更好的方法(使用TreeSet):
<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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lizhifun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值