【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.

解法

三种解法:

  1. 位运算

因为 x^x == 0,所以我们只要把数组里面的和下标都异或起来就知道缺了哪个

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int n = nums.size();
        int res  = n;
        for(int i = 0; i < n; ++i) {
            res ^= i;
            res ^= nums[i];
        }
        return res;
    }
};
  1. 求和
    求出到size+1的和,然后挨个减就好了

  2. 二分法
    判断中间的等于下标不,不等然后接着判断

posted @ 2017-03-25 20:33  mrbean  阅读(119)  评论(0)    收藏  举报