448.Find All Numbers Disappeared in an Array

来源:互联网 发布:成都管家婆软件代理 编辑:程序博客网 时间:2024/06/07 06:25

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]

Subscribe to see which companies asked this question.

first answer(using two loop)
wrong reason: time limit exceeded

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        int s = nums.size();        vector<int> out;        for (int i = 1; i <= s; i++) {            out.push_back(i);        }        int in = 0;        for (int j = 0; j < s; j++) {            if (nums[j] == i)                in++;        }        if (in == 0) {            out.push_back(i);        }        return out;    }};

correct answer:

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

analyse: to avoid using extra space,use the sign symbol of position as the mark to existance.

0 0