[LeetCode] 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]

要求不用额外的空间,以及O(n)的时间。

额,这要求有点高啊。


不过有一个很重要的限制条件:1 ≤ a[i] ≤ n

于是大体思想就是:把数组中的每一个数(设为x),当做数组下标,把下标x处的数a[x]用其相反数-a[x]来代替。(当然,x要做下-1的处理,不然数组会越界)。


class Solution {
public:
	vector<int> findDisappearedNumbers(vector<int>& nums) {
		vector<int> ans;

		for (int n : nums) {
			int val = abs(n) - 1;
			if(nums[val] > 0)
				nums[val] = -nums[val];
		}
		for (int i = 0; i < nums.size(); i++)
			if (nums[i] > 0)
				ans.push_back(i + 1);

		return ans;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值