题目描述:
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]
题目解析:
这道题目的难点在于空间复杂度的把握。我们可以看到数组的大小和数组元素的范围一致,因此可以借用这个存储信息。遍历整个数组,将元素的值存储在数组下标,例如元素值为3,则使得下标2处的值为负数。因此在第二次遍历数组时,若值为负数,则表示该下标值在原来数组是有的。
代码如下:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < nums.size(); ++i) {
int m = abs(nums[i]) - 1;
nums[m] = -abs(nums[m]);
}
vector<int > result;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) {
result.push_back(i + 1);
}
}
return result;
}
};