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]

解题思路:

遍历输入数组,在输出数组上计数,遍历输出数组,将值为0的下表加1依次添加到输出数组中,最终改变输出数组的大小。

代码:

 1 class Solution {
 2 public:
 3     vector<int> findDisappearedNumbers(vector<int>& nums) {
 4         vector<int> ret(nums.size(), 0);
 5         for (auto num : nums) {
 6             ret[num-1]++;
 7         }
 8         int i = 0, j = 0;
 9         for (; i < ret.size(); i++) {
10             if (ret[i] == 0) {
11                 ret[j++] = i+1;
12             }
13         }
14         ret.resize(j);
15         return ret;
16     }
17 };
View Code
原文地址:https://www.cnblogs.com/gsz-/p/9544760.html