[LeetCode] Find All Numbers Disappeared in an Array 找出数组中全部消失的数字 LeetCode All in One 题目讲解汇总(持续更新中...

 

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.html

Find all the elements of [1, n] inclusive that do not appear in this array.java

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:app

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

Output:
[5,6]

 

这道题让咱们找出数组中全部消失的数,跟以前那道Find All Duplicates in an Array极其相似,那道题让找出全部重复的数字,这道题让找不存在的数,这类问题的一个重要条件就是1 ≤ a[i] ≤ n (n = size of array),否则很难在O(1)空间和O(n)时间内完成。三种解法也跟以前题目的解法极其相似。首先来看第一种解法,这种解法的思路路是,对于每一个数字nums[i],若是其对应的nums[nums[i] - 1]是正数,咱们就赋值为其相反数,若是已是负数了,就不变了,那么最后咱们只要把留下的整数对应的位置加入结果res中便可,参见代码以下:post

 

解法一:this

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        for (int i = 0; i < nums.size(); ++i) {
            int idx = abs(nums[i]) - 1;
            nums[idx] = (nums[idx] > 0) ? -nums[idx] : nums[idx];
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] > 0) {
                res.push_back(i + 1);
            }
        }
        return res;
    }
};

 

第二种方法是将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中便可,参见代码以下:url

 

解法二:spa

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] != nums[nums[i] - 1]) {
                swap(nums[i], nums[nums[i] - 1]);
                --i;
            }
        }
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] != i + 1) {
                res.push_back(i + 1);
            }
        }
        return res;
    }
};

 

下面这种方法是在nums[nums[i]-1]位置累加数组长度n,注意nums[i]-1有可能越界,因此咱们须要对n取余,最后要找出缺失的数只须要看nums[i]的值是否小于等于n便可,最后遍历完nums[i]数组为[12, 19, 18, 15, 8, 2, 11, 9],咱们发现有两个数字8和2小于等于n,那么就能够经过i+1来获得正确的结果5和6了,参见代码以下:code

 

解法三:htm

class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            nums[(nums[i] - 1) % n] += n;            
        }
        for (int i = 0; i < n; ++i) {
            if (nums[i] <= n) {
                res.push_back(i + 1);
            }
        }
        return res;
    }
};

 

相似题目:

Find All Duplicates in an Array

First Missing Positive

 

参考资料:

https://discuss.leetcode.com/topic/65944/c-solution-o-1-space

https://discuss.leetcode.com/topic/66063/5-line-java-easy-understanding

 

LeetCode All in One 题目讲解汇总(持续更新中...)

相关文章
相关标签/搜索