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]
代码如下:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for(int i=0;i<nums.size();i++){
int temp = abs(nums[i])-1;
nums[temp] = nums[temp]>0? -nums[temp]:nums[temp];
}
vector<int> result;
for(int i=0;i<nums.size();i++){
if(nums[i]>0){
result.push_back(i+1);
}
}
return result;
}
};
差不多也是找序列中重复数字的题。
如果一个数字重复出现了两次,那么数列中偏移对应位置处的数字会是一个正数,这种策略能够将算法复杂度降到O(n).