数组的去重与排序

来源:互联网 发布:淘宝怎么卖二手东西 编辑:程序博客网 时间:2024/04/28 01:26

做在线编程题遇到一道题,发现有比较好的实现思路,就记录下来了。
题目描述
给定N个1-1000之间的数字,对于其中重复的数字只保留一个,其余的去除掉。

输入描述:
输入多行,先输入整数的个数,然后再输入相应的整数。

输出描述
返回多行处理后的结果。

例子
输入:

6122312351

输出:

151223

我的答案:

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class Main{    public static void main(String[] args) {        Scanner scan = new Scanner(System.in);        while(scan.hasNext()){            int count = scan.nextInt();            int[] ary = new int[count];            for(int i =0;i<count;i++){                ary[i]=scan.nextInt();            }            boolean flag;             List<Integer> result = new ArrayList<>();             for(int i =0;i<count;i++){                flag = false;                for(int j =0;j<result.size();j++){                    if(ary[i]==(result.get(j))){                        flag=true;                    }                }                if(!flag){                    result.add(ary[i]);                }            }            Integer[] res= result.toArray(new Integer[result.size()]);            Arrays.sort(res);            for(int s :res){                System.out.println(s);            }        }    }}

其他版本的答案:
1.采用set集合的:

import java.util.Scanner;import java.util.TreeSet;public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        while(sc.hasNext()){            int num = sc.nextInt();            TreeSet<Integer> set = new TreeSet<Integer>();            for(int i = 0 ; i < num ;i++){                int curr = sc.nextInt();                set.add(curr);            }            for(Integer i : set){                System.out.println(i);            }        }    }}

2.桶排序

import java.util.Scanner;public class test01 {    public static void main(String[] args) {        Scanner scan = new Scanner(System.in);        while(scan.hasNext()) {            int n = scan.nextInt();            int[] a = new int[n];            for(int i = 0; i < n; i++) {                a[i] = scan.nextInt();            }            int[] c = qucong(a);            for(int i = 0; i < 1000; i++) {                if(c[i] == 1) {                    System.out.println(i);                }            }        }    }    public static int[] qucong(int[] a) {        int[] b = new int[1000];        for(int i = 0; i < 1000; i++) {            b[i] = 0;        }        for(int i = 0; i < a.length; i++) {            b[a[i]] = 1;        }        return b;    }} 
0 0