【主要考察点】:哈希表
解题方法
1. 哈希表
直接利用哈希表判断元素是否存在
class Solution {
public List<Integer> findDisappearedNumbers1(int[] nums) {
int n = nums.length;
Set<Integer> set = new HashSet<>();
for(int num : nums){
set.add(num);
}
List<Integer> result = new ArrayList<>();
for(int i = 1; i <= n; i++){
if(!set.contains(i)){
result.add(i);
}
}
return result;
}
}
2. 原地修改
哈希表使用到了额外的空间,我们也可以模拟哈希表的实现方式,直接修改数组,然后通过取模的方式,也能保证落在同一个数组下标上。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
for(int i = 0; i<n; i++){
// 找到当前数本应该在的下标位置
int k = (nums[i]-1) % n;
// 加上n,不影响取模后得到的结果
nums[k] += n;
}
List<Integer> result = new ArrayList<>();
for(int i = 0; i<n; i++){
// 如果当前下标值小于等于n,则表示当前位置上的元素未出现过。
if(nums[i] <= n){
result.add(i+1);
}
}
return result;
}
}