题目:
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. 因为n >= 1, 则输入不空,没有要单独处理的边界情况
2. 我的方法是有限次遍历数组。
将位置 i 的值放到它应该在的位置,如果所有的值只出现一次,则形成一个递增的数列为 1 - n (当然不可能,哈哈)
什么时候结束:
只有一次的值已经正确放置,缺少的值被其他值占用。当检测到想替换的值已经放置到正确位置时,终止。
然后再遍历一次找出缺值即可。(叙述有点乱。。。还是看代码吧,还没看讨论区的解法,网速太差。。。)
代码:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
bool flag = true;
while (flag){
flag = false;
for (int i = 0; i < nums.size(); i++){
if (nums[i] != i + 1 && nums[i] != nums[nums[i] - 1]){
swap(nums[i], nums[nums[i] - 1]);
flag = true;
}
}
}
for (int i = 0; i < nums.size(); i++)
if (nums[i] != i + 1)
res.push_back(i + 1);
return res;
}