[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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索