Find All Numbers Disappeared in an Array【找到数组中未出现的元素】

PROBLEM:

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]

SOLVE:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        for(int i=0;i<nums.size();i++){
            int m=abs(nums[i])-1;
            nums[m]=nums[m]>0?-nums[m]:nums[m];
        }
        for(int i=0;i<nums.size();i++){
            if(nums[i]>0)
                res.push_back(i+1);
        }
        return res;
    }
};

解释:利用输入数组,每便利到一个数,找到比该值绝对值(因为该值可能在之前的循环中被置为负数)小1的下标处的元素,将其改为负数;第二次遍历时,值为负数对应的下标加1就是缺失的值。

猜你喜欢

转载自blog.csdn.net/sim0hayha/article/details/80453372