題目名稱
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)中所有元素進行異或串連操作,肯定能得到缺失的那個數字。