Java训练work3.Exer3---去重与排序

【问题描述】明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作。Input Param n 输入随机数的个数 inputArray n 个随机整数组成的数组 Return Value OutputArray 输出处理后的随机整数

【输入形式】输入多行,先输入随机整数的个数n,再输入相应个数的整数

【输出形式】输出一行,处理后的结果

【样例输入】 11

         10 20 40 32 67 40 20 89 300 400 15 

【样例输出】10 15 20 32 40 67 89 300 400

解法一:系统排序,手动去重

	public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();
        int[] arr = new int[N];
        for(int i=0;i<N;i++)
            arr[i] = scan.nextInt();
        Arrays.sort(arr);
        int flags = arr[0];
        for(int i=0;i<N;i++)
        {
            if(i==0)
                System.out.print(arr[i] + " ");
            else
            {
                if(arr[i]==flags)
                    continue;
                else
                {
                    System.out.print(arr[i] + " ");
                    flags = arr[i];
                }
            }
        }
        scan.close();
    }

解法二:利用TreeSet数据结构,自动排序加去重

		public static void main(String[] args)
        {
	        Scanner scan = new Scanner(System.in);
	        int N = scan.nextInt();
	        int[] arr = new int[N];
	        for(int i=0;i<N;i++)
	            arr[i] = scan.nextInt();
	        TreeSet set = new TreeSet(new Comparator()
	        {
	            @Override
	            public int compare(Object o1,Object o2)
	            {
	                if(o1 instanceof Integer&& o2 instanceof Integer)
	                {
	                    Integer i1 = (Integer)o1;
	                    Integer i2 = (Integer)o2;
	                    return i1.intValue()-i2.intValue();
	                }
	                throw new RuntimeException();
	            }
	        });
	        for(int i=0;i<N;i++)
	        {
	            set.add(arr[i]);
	        }
	        for(Object o : set)
	        {
	            if(o instanceof Integer)
	            {
	                Integer i = (Integer)o;
	                System.out.print(i.intValue());
	                System.out.print(" ");
	            }
	            else
	                throw new RuntimeException();
	        }
	        scan.close();
	  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值