PROBLEM:
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]
SOLVE:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
for(int i=0;i<nums.size();i++){
int m=abs(nums[i])-1;
nums[m]=nums[m]>0?-nums[m]:nums[m];
}
for(int i=0;i<nums.size();i++){
if(nums[i]>0)
res.push_back(i+1);
}
return res;
}
};解释:利用输入数组,每便利到一个数,找到比该值绝对值(因为该值可能在之前的循环中被置为负数)小1的下标处的元素,将其改为负数;第二次遍历时,值为负数对应的下标加1就是缺失的值。
本文介绍了一种高效查找数组中丢失数字的方法,通过两次遍历数组,巧妙地利用数组本身作为辅助空间来标记出现过的数字,最终找出未出现的数字。
524

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



