leetCode刷题归纳-Array(448. Find All Numbers Disappeared in an Array Add to List)

本文介绍了一种高效查找数组中缺失元素的方法,通过标记数组中的数值来实现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.

Example:

Input: [4,3,2,7,8,2,3,1]

Output: [5,6]

解决代码:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int len=nums.size();
        for (int i=0;i<len;i++){
            int m=abs(nums[i])-1;//关于这个地方为什么一定要加绝对值,因为前面的步骤可能把正值变成了负值,索引会错误
            nums[m]=nums[m]>0?-nums[m]:nums[m];
        }
         vector<int> result;
        for (int i=0;i<len;i++){
            if (nums[i]>0)
                result.insert(result.end(),i+1);
        }

        return result;   
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值