Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
题目好简单的 不过有时间限制 暴力遍历肯定不行
所以用集合来做,用contain方法来判断 这样时间空间效率都是O(n²)
public boolean containsDuplicate(int[] nums) {
HashMap<Integer, Integer> hm = new HashMap<>();
int x = 0;
for (int i=0; i<nums.length; i++) {
x = nums[i];
if (!hm.containsKey(x)) {
hm.put(x, i);
} else {
return true;
}
}
return false;
}
当然还有一个更聪明的办法,就是用array中是sort方法,heap sort可以帮助我们快速将数组排序,到时候只要比较nums[i] == nums[i++]就好了