题目描述:
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]
一个数组有n个数,每个数都在[1,n]的范围内,有的数出现一次,有的数出现两次,求1~n中没有出现的数,时间复杂度为O(n),不能用额外空间。由于数组元素大小的特殊性,可以令元素的值作为下一个元素的下标形成链表,依次遍历的时候对每个遍历到的元素做标记,而在数组中没有标记的元素的下标即为所求,那么要做标记同时保证不真正影响元素的值的最简单的方法就是取负数。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for(int i=0;i<nums.size();i++)
{
nums[abs(nums[i])-1]=-abs(nums[abs(nums[i])-1]);
}
vector<int> result;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>0) result.push_back(i+1);
}
return result;
}
};