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]
代码如下:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for(int i=0;i<nums.size();i++){
int temp = abs(nums[i])-1;
nums[temp] = nums[temp]>0? -nums[temp]:nums[temp];
}
vector<int> result;
for(int i=0;i<nums.size();i++){
if(nums[i]>0){
result.push_back(i+1);
}
}
return result;
}
};
差不多也是找序列中重复数字的题。
如果一个数字重复出现了两次,那么数列中偏移对应位置处的数字会是一个正数,这种策略能够将算法复杂度降到O(n).
寻找未出现的数字
本文介绍了一种在不使用额外空间且时间复杂度为O(n)的情况下找出数组中缺失数字的方法。通过遍历数组并利用负数标记已出现的数字,最终找出所有未出现的数字。
412

被折叠的 条评论
为什么被折叠?



