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?

思路:我的方法是根据nums数组的大小,先计算出如果没有数缺少时所有数的和,利用公式 n * (n + 1) / 2即可。但这样会有溢出的危险。

看了discussion之后,被里面利用位运算的答案所深深震撼。

其主要思路就是,如果现在的数组里有一个数缺失,那么我们将这些数进行异或运算,然后再异或一遍完整的数。

那么没有缺失的数将会被异或两遍,而缺失的则只会被异或一遍。最后异或完的结果就是缺失的数字!

1 class Solution {
2 public:
3     int missingNumber(vector<int>& nums) {
4         int res = 0;
5         for (int i = 0, n = nums.size(); i < n; i++)
6             res ^= nums[i] ^ (i + 1);
7         return res;
8     }
9 };
原文地址:https://www.cnblogs.com/fenshen371/p/4913740.html