pta运行超时如何解决

pta运行超时
题目如下

在一大堆数据中找出重复的是一件经常要做的事情。现在,我们要处理许多整数,在这些整数中,可能存在重复的数据。

你要写一个程序来做这件事情,读入数据,检查是否有重复的数据。如果有,去掉所有重复的数字。最后按照输入顺序输出没有重复数字的数据。所有重复的数字只保留第一次出现的那份。

输入格式:
你的程序首先会读到一个正整数 n,1≤n≤100000。
然后是 n 个整数,这些整数的范围是 [1, 100000]。

输出格式:
在一行中按照输入顺序输出去除重复之后的数据。每两个数据之间有一个空格,行首尾不得有多余空格。
输入样例:
5
1 2 2 1 4
输出样例:
1 2 4
代码长度限制
16 KB
时间限制
1500 ms
内存限制
150 MB

img


img


img


有没有懂哥知道如何在我这个代码的基础上修改一下,让运行时长缩短。

典型的去重问题,建议你使用set集合来解决


            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = scanner.nextInt();
            }
            Set<Integer> set = new HashSet<>();
            for (int j = 0; j < n; j++) {
                set.add(a[j]);
            }
            Iterator iterator = set.iterator();
            StringBuffer stringBuffer = new StringBuffer();
            while (iterator.hasNext()) {
                stringBuffer.append(" ").append(iterator.next());
            }
            System.out.println(stringBuffer.toString().replaceFirst(" ", ""));