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

排序

Posted by JinFei on March 5, 2021

题目描述

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.

Example1:

Input: [4,3,2,7,8,2,3,1]

Output:
[5,6]

解题思路

  • 将nums[i]置换到其对应的位置nums[nums[i]-1]上去
  • 比如对于没有缺失项的正确的顺序应该是[1, 2, 3, 4, 5, 6, 7, 8],而我们现在却是[4,3,2,7,8,2,3,1]
  • 我们需要把数字移动到正确的位置上去,比如第一个4就应该和7先交换个位置,以此类推,最后得到的顺序应该是[1, 2, 3, 4, 3, 2, 7, 8]
  • 我们最后在对应位置检验,如果nums[i]和i+1不等,那么我们将i+1存入结果res中即可
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        // swap
        int size = nums.size();
        for(int i = 0; i < size; i++){
            if(nums[i] != nums[nums[i] - 1]){
                swap(nums[i], nums[nums[i] - 1]);
                --i;
            }
        }
        for(int i = 0; i < size; i++){
            if(nums[i] != i + 1){
                res.push_back(i + 1);
            }
        }
        return res;
    }
};