给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,那么程序打印true;
如果数组中每个元素都不相同,则程序打印false ;
示例1:
输入:[1,2,3,1]
输出: true
示例2:
输入:[1,2,3]
输出: false
要求:
不可直接调用java已经封装好Arrays工具类;
严格按照用例的输入输出形式;
尽量使用多种方法解决;
可上交博客链接或直接交图片
第一次看到这个题目我有三种思路:
1.穷举
2.排序
3.集合去重
因为用集合最简单,所以我使用了集合
import java.util.*;
public class ArrayToSet {
public static void main(String[] args) {
// 创建数组
int[] a = new int[9999];
Scanner read = new Scanner(System.in);
String s = read.nextLine();
Scanner reader = new Scanner(s);
int i = 0;
while (reader.hasNextInt()) {
a[i] = reader.nextInt();
i = i + 1;
}
// 创建集合
HashSet sites = new HashSet<>();
for (int j : a) {
sites.add(j);
}
// 去掉数组默认的0
sites.remove(0);
// 利用集合元素不相同去重,再比较数组和集合的长度,如果长度不一说明有元素被去重
if (sites.size() == i) {
System.out.println("false");
} else {
System.out.println("true");
}
}
}
4.运行结果



