[LeetCode] Missing Number

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?

 给定一个容量为n的数组,里面包含从0, 1, 2, ..., n,找出丢失的数字。利用XOR数组中的每一个数,然后让这个结果遍历数字0~n即得到丢失的数。

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int res = 0;
        int n = nums.size();
        vector<int> tmp;
        for (int num : nums)
            res ^= num;
        while (n)
            res ^= n--;
        return res;
    }
};
// 26 ms
原文地址:https://www.cnblogs.com/immjc/p/7200690.html