LeetCode:448. Find All Numbers Disappeared in an Array
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 ≤ a[i] ≤ n ,n为数组长度,一些元素出现一次或者两次。要求找出[1,n]中没有出现在数组中的元素,不允许使用额外的空间,并且时间复杂度为O(n)。
由于不能使用额外空间,并且 1 ≤ a[i] ≤ n ,那么可以使用数组的下标来表示[1,n]。首先扫描array,a[i]出现了,那么我们找到下标为a[i]的元素,将其变为负数,表示下标a[i]出现过。再次扫描array,如果某个元素为正,那么它对应的下标没有出现在数组中,则把它加入最后所求的答案中。
class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { for(auto num:nums) { int index=abs(num)-1; nums[index]=-abs(nums[index]); } vector<int> res; for(int i=0;i<nums.size();i++) { if (nums[i]>0) { res.push_back(i+1); } } return res; } };