给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/
思路
由于不能使用额外空间,因此哈希表不能用,则很容易想到排序,时间复杂度O(nlogn)。
官方给的思路很有意思,由于数字区间为[1,n],正好可以利用下标来表示这些值:
若nums[i]的存在,记录在数组nums[nums[i]-1]上,将其加一个负号;最后遍历一遍数组,如果有元素为正,则下标+1的值是消失的。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int len = nums.size();
for(int i=0; i<len; ++i){
int idx = abs(nums[i]) - 1;
if(nums[idx]>0){
nums[idx] = -nums[idx];
}
}
vector<int> res;
for(int i=0; i<len; ++i){
if(nums[i]>0){
res.push_back(i+1);
}
}
return res;
}
};