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]

给出n个数,其中1~n中有些数没出现,求这些没出现的数。

我们可以将数值和数组的标关联,运用负号巧妙的解决了这个问题。确保每个出现过的数都变成负数

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

 

posted on 2017-07-28 15:58  Beserious  阅读(146)  评论(0编辑  收藏  举报