1,题目要求
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≤a[i]≤n(n =数组的大小),一些元素出现两次,其他元素出现一次。
查找未出现在此数组中的[1,n]包含的所有元素。
你可以在没有额外空间和O(n)运行时的情况下完成吗? 您可能认为返回的列表不计入额外空间。
2,题目思路
对于这道题,题目要求找出长度为n的数组,为出现在[1, n]的数组,这也就意味着,一定有数字出现的次数超过1,而有些数字没有出现。
如果不设置内存的要求,那么可以直接定义一个hash表来记录每个数字出现的次数,然后对hash表遍历以便,就可以得到没有出现的数字。
而如果我们不希望申请额外的内存,那么就需要在原数组上做修改,以记录。
思路是这样,我们可以将每一位上的数字,以正负的形式来表示是否出现过,即:
如果nums[1] = 4,nums[3] = 2,那么,我们就可以让nums[4-1] = -nums[4-1],即nums[3] = -2,这样,既可以记录数字4出现过了(取了负),又不会对之后的遍历有影响(nums[3]的绝对值仍为2)。
这样,当我们对整个数组遍历了一遍之后,就可以得到,没出现的数字,在对应位置上的数值一定是正的。
3,代码实现
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res {};
for(auto &n : nums)
{
int index = abs(n)-1;
if(nums[index]>0)
nums[index] = -nums[index];
}
for(int i = 0;i<nums.size();i++)
{
if(nums[i]>0)
res.push_back(i+1);
}
return res;
}
};