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]

题意:给一个a[n]数组,里面的数在1到n之间,并且相同的元素出现的次数不超过2,从1到n中找出不在数组中出现过得数。

要求不使用额外的空间,且时间复杂度为O(n)。返回的数组不算额外空间。

分析:不使用额外的空间,那么就在元素组上求,注意下标和元素值的关系,我们可以把对应的元素放在对应的位置,最后判断数组中的值与下标是否对应。为了保证时间复杂度,肯定不能使用二重循环,我们可以采用将交换的方法,一次将一个元素放在对应的位置,这样就保证了时间复杂度。

代码:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int n=nums.size();
        int i=0;
        while(i!=n)
        {
            if(nums[i]==nums[nums[i]-1])
            {
                i++;
            }
            else
            {
                int temp=nums[nums[i]-1];
                nums[nums[i]-1]=nums[i];
                nums[i]=temp;
            }
        }
        vector<int> disp;
        for(int i=0;i<n;i++)
        {
            if(nums[i]!=i+1)
                disp.push_back(i+1);
        }
        return disp;
    }
};
逻辑一下就写出来了,关键是下标判断烦人,一不留神就弄错了,搞得我又去debug。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值