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]
题解:
使用鸽巢原理
/**
条件为:
1.每只鸽子都要被使用过(所以不能交换鸽子的位置)
1.1 巢穴里的鸽子的原始样子要能被识别出来,因此巢里的值需要被标记,同时也要能通过一种方式得到其中鸽子的值。
**/
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector <int> res;
for(int i = 0; i < nums.size(); i++){
nums[abs(nums[i]) - 1] = -1 * abs(nums[abs(nums[i]) - 1]);
}
for(int i = 0; i < nums.size(); i++){
if(nums[i] > 0 )
res.emplace_back(i+1);
}
return res;
}
int abs(int num){
if(num > 0) return num;
else return -num;
}
};