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]
题意:给一个a[n]数组,里面的数在1到n之间,并且相同的元素出现的次数不超过2,从1到n中找出不在数组中出现过得数。
要求不使用额外的空间,且时间复杂度为O(n)。返回的数组不算额外空间。
分析:不使用额外的空间,那么就在元素组上求,注意下标和元素值的关系,我们可以把对应的元素放在对应的位置,最后判断数组中的值与下标是否对应。为了保证时间复杂度,肯定不能使用二重循环,我们可以采用将交换的方法,一次将一个元素放在对应的位置,这样就保证了时间复杂度。
代码:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n=nums.size();
int i=0;
while(i!=n)
{
if(nums[i]==nums[nums[i]-1])
{
i++;
}
else
{
int temp=nums[nums[i]-1];
nums[nums[i]-1]=nums[i];
nums[i]=temp;
}
}
vector<int> disp;
for(int i=0;i<n;i++)
{
if(nums[i]!=i+1)
disp.push_back(i+1);
}
return disp;
}
};
逻辑一下就写出来了,关键是下标判断烦人,一不留神就弄错了,搞得我又去debug。