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的数组,遍历所有元素,找出没有出现过的元素。基本思想是我们将元素值作为下标遍历输入数组并标记为负值num[i] = -num[i]。
vector<int> finddisappear(vector<int>& nums){ vector<int>tmp; size_t n = nums.size(); for(size_t i = 0; i < n; i++){ int val = abs(nums[i]) - 1;//nums[i]是所有元素值,val是下标,将元素值出现的下标的元素标记为负值,减1的意思是下标比个数少1 if(nums[val] > 0) nums[val] = -nums[val]; } for(size_t i = 0; i < n; i++){ if(nums[i] > 0) tmp.push_back(i + 1); } return tmp; }
比如4个元素的数组里出现了2,3,那么下标为2,3的元素标为负值,剩下的1,4没有出现,那么仍为正值,找到正值的下标也就是结果了。