问题描述:
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
解题思路:
由于数字范围均在 [1,n]中,我们也可以用一个长度为 nn 的数组来代替哈希表。这一做法的空间复杂度是 O(n)的。我们的目标是优化空间复杂度到 O(1)。
注意到 nums 的长度恰好也为 n,能否让 nums 充当哈希表呢?
由于 nums 的数字范围均在 [1,n] 中,我们可以利用这一范围之外的数字,来表达「是否存在」的含义。
具体来说,遍历nums,每遇到一个数 x,就让nums[x−1] 增加 n。由于nums 中所有数均在 [1,n] 中,增加以后,这些数必然大于 n。最后我们遍历 nums,若nums[i] 未大于 n,就说明没有遇到过数 i+1。这样我们就找到了缺失的数字。
注意,当我们遍历到某个位置时,其中的数可能已经被增加过,因此需要对 nn 取模来还原出它本来的值。
参考文章:
lLeetCode官方
代码实现:
/**
* 使用辅助数组的解法,空间复杂度为O(n)
* @param nums
* @return
*/
public static List<Integer> findDisappearedNumbers(int[] nums) {
LinkedList<Integer> list = new LinkedList<>();
int[] arr = new int[nums.length +1];
for(int i=0; i<nums.length; i++){
arr[nums[i]]++;
}
for(int i=1; i<arr.length; i++){
if(arr[i]==0){
list.add(i);
}
}
return list;
}
/**
* 修改原数组的解法
* @param nums
* @return
*/
public static List<Integer> findDisappearedNumbers2(int[] nums) {
LinkedList<Integer> list = new LinkedList<>();
for(int i=0; i<nums.length; i++){
//注意需要对n,即nums.length取余,防止数组越界
nums[ (nums[i] - 1)%nums.length ] += nums.length;
}
for(int i=0; i<nums.length; i++){
if(nums[i] <= nums.length){
list.add(i+1);
}
}
return list;
}
使用辅助数组提交结果:
修改原数组的提交结果: