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.


思路:

1. 因为n >= 1, 则输入不空,没有要单独处理的边界情况

2. 我的方法是有限次遍历数组。

将位置 i 的值放到它应该在的位置,如果所有的值只出现一次,则形成一个递增的数列为 1 - n (当然不可能,哈哈)

什么时候结束:

只有一次的值已经正确放置,缺少的值被其他值占用。当检测到想替换的值已经放置到正确位置时,终止。

然后再遍历一次找出缺值即可。(叙述有点乱。。。还是看代码吧,还没看讨论区的解法,网速太差。。。)


代码:

vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        bool flag = true;
        while (flag){
            flag = false;
            for (int i = 0; i < nums.size(); i++){
                if (nums[i] != i + 1 && nums[i] != nums[nums[i] - 1]){
                    swap(nums[i], nums[nums[i] - 1]);
                    flag = true;
                }
            }
        }
        for (int i = 0; i < nums.size(); i++)
            if (nums[i] != i + 1)
                res.push_back(i + 1);
        return res;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值