找到所有数组中消失的数字

1.题目

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为*O(n)*的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

2.分析

这题要求找出1到n数租缺少了哪一个,就开一个大小为n的数组,然后遍历nums把每个元素以坐标存在新开的数组中,最后统计看那个坐标的元素为0则就少哪个数。

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
ArrayList<Integer> ans = new ArrayList<>();
int len = nums.length;
int[] count = new int[len+1];
for (int num : nums) {
count[num]+=1;
}
for (int i = 1; i <=len; i++) {
if(count[i]==0){
ans.add(i);
}
}
return ans;
}
}