这是检查整数数组是否包含重复项的正确方法吗?我想传入一个int [] nums而不是Integer [],但是无法使其工作。
public static boolean isUnique(Integer[] nums){
return new HashSet<Integer>(Arrays.asList(nums)).size() == nums.length;
}
答案 0 :(得分:4)
您可以执行以下操作:
public static boolean isUnique(int[] nums){
Set<Integer> set = new HashSet<>(nums.length);
for (int a : nums) {
if (!set.add(a))
return false;
}
return true;
}
这更像是一种短路式的方法,而不是你所拥有的,只要遇到重复就会返回。更不用说它可以根据需要使用int[]
。我们正在利用Set#add
返回一个布尔值的事实,该布尔值指示被添加的元素是否已经存在于集合中。
答案 1 :(得分:0)
此处的设置或排序是否无关紧要,排序更优,更少的对象。
public static boolean isUnique(int[] nums) {
if (nums.length <= 1) {
return true;
}
int[] copy = Arrays.copyOf(nums);
Arrays.sort(copy);
int old = Integer.MAX_VALUE; // With at least 2 elems okay.
for (int num : copy) {
if (num == old) {
return false;
}
old = num;
}
return true;
}
附录评论较慢,但节省内存。