Come from : [https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/]
448. Find All Numbers Disappeared in an Array
1.Question
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]
2.Answer
easy 类型题目。
但是题目要求,不借助 额外的空间,我的代码 不满足这个条件。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> res(nums.size() + 1, 0);
vector<int> tmp;
for(int i = 0; i < nums.size(); ++i)
{
++res[nums[i]];
}
for(int i = 1; i <= nums.size(); ++i)
{
if(res[i] == 0)
{
tmp.push_back(i);
}
}
return tmp;
}
};
3.大神们的解决方案
方法:
将所有正数作为数组下标,置对应数组值为相反数。那么,仍为正数的位置即为(未出现过)消失的数字。
举个例子:
原始数组:[4,3,2,7,8,2,3,1]
重置后为:[-4,-3,-2,-7,8,2,-3,-1]
结论:[8,2] 分别对应的index为[5,6](消失的数字)
vector<int> findDisappearedNumbers(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i)
nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1]);
vector<int> res;
for (int i = 0; i < nums.size(); ++i){
if (nums[i] > 0)
res.push_back(i+1);
}
return res;
}
4.我的收获
2019/5/7 胡云层 于南京 72