存在重复元素
1 判断存在
排序
注意for循环的条件
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
}
时间复杂度 : O(nlogn),即排序的时间复杂度。扫描的时间复杂度 O(n)忽略。
空间复杂度 : O(1),没有用到额外空间。如果深究 Arrays.sort(nums) 使用了栈空间,那就是 O(logn)。
使用set
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer>