[Array]448. Find All Numbers Disappeared in an Array

Posted 两猿社长

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Array]448. Find All Numbers Disappeared in an Array相关的知识,希望对你有一定的参考价值。

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]

思路:给出长度为n的数组,遍历所有元素,找出没有出现过的元素。基本思想是我们将元素值作为下标遍历输入数组并标记为负值num[i] = -num[i]。
vector<int> finddisappear(vector<int>& nums){
vector<int>tmp;
size_t n = nums.size();
for(size_t i = 0; i < n; i++){
int val = abs(nums[i]) - 1;//nums[i]是所有元素值,val是下标,将元素值出现的下标的元素标记为负值,减1的意思是下标比个数少1
if(nums[val] > 0)
nums[val] = -nums[val];
}

for(size_t i = 0; i < n; i++){
if(nums[i] > 0)
tmp.push_back(i + 1);
}
return tmp;
}
比如4个元素的数组里出现了2,3,那么下标为2,3的元素标为负值,剩下的1,4没有出现,那么仍为正值,找到正值的下标也就是结果了。


以上是关于[Array]448. Find All Numbers Disappeared in an Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 448. Find All Numbers Disappeared in an Array & 442. Find All Duplicates in an Array(示例

Leetcode 448. Find All Numbers Disappeared in an Array

#Leetcode# 448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array

448. Find All Numbers Disappeared in an Array