Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
}
posted on 2017-08-14 10:45  英雄与侠义的化身  阅读(97)  评论(0编辑  收藏  举报