Find All Numbers Disappeared in an Array

本文介绍两种高效算法,用于找出数组中缺失的数字。利用数组特性,通过元素交换或标记负数的方法,在O(n)时间内找到所有未出现的数字。

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值