Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
这道题是找数字区间中缺少的数字,题目难度为Easy。
题目和之前某道题描述有些相似,所以一开始就陷入了位操作的陷阱,想了很久没找到解决办法,不知道大家有没有相同的情况-_-!!
其实只需将出现过的数字标记一下就可以了,而这里空间复杂度要求O(1),所以我们要利用原始数组来辅助标记。每遍历到一个数字m,将其m-1作为下标(求余n),在该下标位置的数字上加n,以表示m出现过了,原数组中数字在1~n范围内,所以可以复原原始数字并以n为界来判断数字是否出现过。最终利用数组中仍在1~n范围的数字就可以映射出没出现的数字,数字的下标加1即是没有出现的数字。具体代码:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> ret;
int n = nums.size();
for(int i=0; i<n; ++i) nums[(nums[i]-1)%n] += n;
for(int i=0; i<n; ++i) if(nums[i] <= n) ret.push_back(i+1);
return ret;
}
};