Find All Numbers Disappeared in an Array

來源:互聯網
上載者:User

標籤:appear   and   example   位置   abs   目的   turned   find   維數   

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 其中的數字也都是1~n的 其實這些數字減一即為數組的下標0~n-1

要好好利用數組中數字和數組下標的關係 在一次按照下標遍曆中 既可以按當前下標中的數字為下標 操作對應的數字 標定這個數字已經出現 多次出現 標定一次就好 當然 不同的標定也可以

就例子而言:從數組的第一個下表中的數字開始 4,找到其對應下表4-1:3, 數組中下標為3的地方標定一下 表示數組中(3+1)已經出現過了
      當以這樣的方式標定為完整個數組時 那麼出現過的數字對應的下標的位置都被標定 沒出現過的即沒有被標定 遍曆一次就可以了

代碼:
vector<int> findDisappearedNumbers(vector<int>& nums) {
        vector<int> res;
        if (nums.size()==0)
            return res;
        for (int i=0; i<nums.size();++i)
        {
            int m=abs(nums[i])-1;
           if (nums[m]>0)
                nums[m] = -nums[m];
        }
        for (int i=0; i<nums.size();++i)
        {
            if (nums[i]>0)
                res.push_back(i+1);
        }
        return res;
    }

Find All Numbers Disappeared in an Array

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.