leetcode_c++:Missing Number(268)

题目

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-1个元素的数列,由0~n个元素去掉一个元素后构成,找出去掉的元素


算法

O(N)
求和,然后和0~n的和做差,差值就是所求。


class Solution {
public:
    int missingNumber(vector<int>& nums) {
        long long len=nums.size();
        long long sum=len*(len+1)/2,sum2=0;
        for(auto i:nums)
            sum2+=i;
        return sum-sum2;

    }
};

算法

异或
x^a^a=x,缺失的数会留下

两个相同的数异或结果是0.

0和其他数异或结果还是那个数。


这里写代码片

你可能感兴趣的:(leetcode(c++))