268. Missing Number

268. 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?

题意: 从0..n中随机选n个不同的数入数组, 注意:数组乱序. 找出缺失的那个数.
三种方法, XOR, sum, 二分查找(要求数组sorted).

人家牛逼想法:XOR
XOR 相同为0不同为1.
0 ^ 1 ^ 2 ^ 3 ^ 2 ^ 1 ^ 0 = 3.

(O(n)) time, (O(1)) extra space. 比下面的sum还快.

// xor 位运算
int missingNumber(vector<int>& A) {
    int re = 0;
    for (int i = 1; i <= A.size(); i++)
        re = re ^ i ^ A[i - 1];
    return re;
}

SUM方法:
(O(n)) time, (O(1)) extra space.

// 0..size()和 - 数组和
int missingNumber(vector<int>& A) {
    int sum = 0, n = A.size();
    for (int i = 0; i < n; i++)
        sum += A[i];
    int re = (n * (n + 1)) / 2 - sum;
    return re;
}
原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7356536.html