Find All Numbers Disappeared in an Array

来源:互联网 发布:淘宝信誉提升 编辑:程序博客网 时间:2024/05/01 13:28

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.

无论哪种方法,都充分利用1 ≤ a[i] ≤ n条件。

方法1:数组元素不断交换,以索引为i中元素的值应是i+1为原则进行交换,最后遍历数组当索引为i中元素的值不为i+1时,讲i+1加入到结果中。

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        vector<int> res;        for(int i = 0 ; i < nums.size(); ++i ){            if(nums[i]-1 == i)                continue;            int index = nums[i] -1 ;            while(nums[index]!=index+1){                swap(nums[index],nums[i]);                index = nums[i] - 1;            }        }        for(int i = 0 ; i < nums.size(); ++ i){            if(nums[i]!=i+1)                res.push_back(i+1);        }        return res;    }};

方法2:遍历数组中的元素,利用数组中的元素所形成的下标,将该下标下的数字设置为负数,最后遍历数组若某索引i中的元素大于0,则将i+1插入到结果中。这种方法对数组的改动较小(即添加一个符号),易于恢复。

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