448. Find All Numbers Disappeared in an Array

本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下寻找数组中消失数字的方法。利用数组元素值与下标的关系,通过遍历并修改数组元素的正负来标记已出现的数字,最后再次遍历数组,找出仍为正数的元素对应的下标即为消失的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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]
题目解析:

这道题目的难点在于空间复杂度的把握。我们可以看到数组的大小和数组元素的范围一致,因此可以借用这个存储信息。遍历整个数组,将元素的值存储在数组下标,例如元素值为3,则使得下标2处的值为负数。因此在第二次遍历数组时,若值为负数,则表示该下标值在原来数组是有的。

代码如下:

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        int n = nums.size();
        for (int i = 0; i < nums.size(); ++i) {
            int m = abs(nums[i]) - 1;
            nums[m] = -abs(nums[m]);
        }
        vector<int > result;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] > 0) {
                result.push_back(i + 1);
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值