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]
思路:
设置一个值j,从1自增到数组长度那么大的数,在j自增的过程中若是数组中缺少的数,则为输出数组的值
1,判断第一个数是不是与j相同,如果不是,则j自增到A[0],并将其中的数加入到数组中
2,第二个数开始,判断当前的值A[i]与前一个值A[i-1]是否相同,若是,则j--(因为每次循环j都会自增1,j--是取消j的前一次递增)。
若不是与前一个数相同,则j自增到A[i],并将其中的数加入到数组中
#pragma once
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<int> n;
int j=1;
for (int i = 0; i < nums.size(),j<= nums.size(); i++,j++ )
{
//第一个数的时候,由于是第一个数,必须为1,且之前不会与其他数重复
if (nums[i]!=j&&i==0)
{
while (nums[i] != j&& j <= nums.size())
{
n.push_back(j);
j++;
}
}
else if (i > 0)
{
//第一个数往后的时候
//若是和前面的数相等,则j会自减1
if (nums[i] == nums[i - 1]&&i!=nums.size()-1)
{
j--;
}
while (nums[i] != j&&j<=nums.size())
{
n.push_back(j);
j++;
}
}
}
return n;
}
};