LeetCode 448. Find All Numbers Disappeared in an Array
Given an array nums of n integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
Example 2:
Input: nums = [1,1]
Output: [2]
method
用哈希表存储所有数,然后从1到n开始查找看哪个数不存在
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
unordered_set<int> st;
for (auto n : nums) st.insert(n);
for (int i = 1; i <= nums.size(); i++) {
if (!st.count(i)) res.push_back(i);
}
return res;
}
空间复杂度:$O(n)$
改进:直接以原数组作为哈希表,如果某个数x
存在,就让nums[x-1]+n
,这样加一遍之后,所有元素的范围会由[1,n]
变成[n+1,2n]
,所以小于这个范围的数的index+1
就是缺失的数
可能x
已经被加过了,所以需要取模,nums[(x-1)%len]+n
vector<int> findDisappearedNumbers(vector<int>& nums) {
int len = nums.size();
for (auto n : nums) {
int index = (n - 1) % len;
nums[index] += len;
}
vector<int> res;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] <= len) res.push_back(i + 1);
}
return res;
}
空间复杂度:$O(1)$
举例:最后只有index=3
的小于len
,所以结果为index+1=4