Missing Number(講解一個非常好的方法)

來源:互聯網
上載者:User

題目名稱
Missing Number—LeetCode連結

描述
Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

分析
  考慮到將原數組排序後,如果不缺失元素,數組下標值和元素值是相等的,所以常規思路就是將數組排序,然後根據位置尋找,如果丟失的是最後一個數字,則返回最後一個數字;否則從數組頭部開始遍曆,直到找到值與下標不相符的,返回下標數字。

C++代碼

class Solution {public:    int missingNumber(vector<int>& nums) {        sort(nums.begin(),nums.end());        int size = nums.size();        if(nums[size-1]==size-1)            return size;        for(int i=0;i<size;i++){            if(nums[i]!=i)                return i;        }    }};

總結
  這裡給出一個非常棒的答案,不需要將原數組排序,而採用異或操作符^。先給出代碼,再做解釋:

class Solution {public:    int missingNumber(vector<int>& nums) {        int result = 0;        for (int i = 0; i < nums.size(); i++)            result ^= nums[i]^(i+1);        return result;    }};

The operation of xor is commutative and associative. That is A ^ B = B^A and (A ^ B) ^ C = A ^ (B ^ C). Therefore, A^C^B^A^C = A^A^C^C^B = B. So for this code, the order of the numbers does not matter at all.
  上段內容是這個代碼的作者的解釋,很好懂,舉個例子,給定一個數組:

4,2,0,1

  result初始值為0,做異或操作就是:0^(4^1)^(2^2)^(0^3)^(1^4)=3.
  答案看上去很巧妙,其實思路很簡單,給定的數組肯定缺失一個數字,那麼我對數組所有元素(4,2,0,1)和不缺失的情況(0,1,2,3,4)中所有元素進行異或串連操作,肯定能得到缺失的那個數字。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.