题目:
给定一个包含 n + 1 个整数的数组 nums ,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。
假设 nums 只有 一个重复的整数 ,找出 这个重复的数 。
你设计的解决方案必须不修改数组 nums 且只用常量级 O(1) 的额外空间。
示例 1:
输入:nums = [1,3,4,2,2]
输出:2
示例 2:
输入:nums = [3,1,3,4,2]
输出:3
示例 3:
输入:nums = [1,1]
输出:1
示例 4:
输入:nums = [1,1,2]
输出:1
提示:
1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums 中 只有一个整数 出现 两次或多次 ,其余整数均只出现 一次
进阶:
如何证明 nums 中至少存在一个重复的数字?
你可以设计一个线性级时间复杂度 O(n) 的解决方案吗?
思路一:
将数组进行排序
在左右进行一一判断
class Solution {
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]) return nums[i];
}
return -1;
}
}
判断两个数组是否相等,还可以通过数组的异或
class Solution {
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if((nums[i-1] ^ nums[i])==0){
return nums[i];
}
}
return -1;
}
}
注意初始条件和结束条件会影响前后的位置
思路二:
使用哈希表set进行遍历
class Solution {
public int findDuplicate(int[] nums) {
Set <Integer> set=new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])) return nums[i];
else set.add(nums[i]);
}
return -1;
}
}
单独使用add函数进行遍历添加判断
class Solution {
public int findDuplicate(int[] nums) {
Set <Integer> set=new HashSet<Integer>();
for(int i=0;i<nums.length;i++){
if(!set.add(nums[i])) return nums[i];
}
return -1;
}
}
这是错误情况,添加add之后,在contains判断
逻辑错误
错误情况
class Solution {
public int findDuplicate(int[] nums) {
Set <Integer> set=new HashSet<Integer>();
for(int num:nums)set.add(num);
for(int i=0;i<nums.length;i++){
if(!set.contains(nums[i])) return nums[i];
}
return -1;
}
}