给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入: [4,3,2,7,8,2,3,1]
输出: [5,6]
暴力(有点shadiao)
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=1; i<=nums.length; i++){
map.put(i,0);
}
for(int num:nums){
map.put(num, map.get(num)+1);
}
List<Integer> list = new ArrayList<>();
for(int i=1; i<=nums.length; i++){
if(map.get(i) == 0){
list.add(i);
}
}
return list;
}
}
原地排序
- 原地重新排序,尽量使 nums[i] 的值为 i+1(数据范围是1~n,所以 nums[1] 的位置上应该是 2)
- while 循环的终止条件有两个,满足任一个就终止: 以 i=0 时为例
- 1.数字正确摆放,nums[0] = 1
- 2.数字不正确摆放,但数字正确位置上已经有了正确的数字(两个数字相等,交换不动),例如 nums[0] = 2, nums[2] = 3
for(int i=0; i<nums.length; i++){
while(nums[i] != i+1 && nums[i] != nums[nums[i]-1]){ //swap直到正确摆放
int t = nums[i];
nums[i] = nums[nums[i]-1];
nums[t-1] = t; //nums[nums[i]-1] = t;是错误的,因为nums[i]已在上一行改变
}
}
List<Integer> list = new ArrayList<>();
for(int i=0; i<nums.length; i++){ //遍历,在 i 位置不正确的数就是缺失的
if(nums[i] != i+1){
list.add(i+1);
}
}
return list;
- 原来:[4,3,2,7,8,2,3,1]
- 之后:[1,2,3,4,3,2,7,8]
原地修改二:负值
- 可以在输入数组本身以某种方式标记已访问过的数字,然后再找到缺失的数字
for (int i = 0; i < nums.length; i++) {
int newIndex = Math.abs(nums[i]) - 1;
if (nums[newIndex] > 0) {
nums[newIndex] *= -1;
}
}
List<Integer> result = new LinkedList<Integer>();
for (int i = 1; i <= nums.length; i++) {
if (nums[i - 1] > 0) {
result.add(i);
}
}
return result;
- 原来:[4,3,2,7,8,2,3,1]
- 之后:[-4,-3,-2,-7, 8,2, -3,-1]