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]


本题在一维数组中找到按顺序缺失的数字 按照思维 首先最容易想到的是哈希 那样子的话 很容易得到重复的数字和缺失的数字 可是本题中不允许使用额外的空间
同时 如果简单的使用哈希 也并没有应用到本题中题目的特性 本题题目中 一维数组大小为n 其中的数字也都是1~n的 其实这些数字减一即为数组的下标0~n-1

要好好利用数组中数字和数组下标的关系 在一次按照下标遍历中 既可以按当前下标中的数字为下标 操作对应的数字 标定这个数字已经出现 多次出现 标定一次就好 当然 不同的标定也可以

就例子而言:从数组的第一个下表中的数字开始 4,找到其对应下表4-1:3, 数组中下标为3的地方标定一下 表示数组中(3+1)已经出现过了
      当以这样的方式标定为完整个数组时 那么出现过的数字对应的下标的位置都被标定 没出现过的即没有被标定 遍历一次就可以了

代码:
vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        if (nums.size()==0)
            return res;
        for (int i=0; i<nums.size();++i)
        {
            int m=abs(nums[i])-1;
            if (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;
    }
原文地址:https://www.cnblogs.com/weiyi-mgh/p/6413551.html