leetcode 268 Missing Number(异或运算的应用)

时间:2023-03-10 01:19:25
leetcode 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的和s,再求数组的和s2,s-s2就是少的那个数。

由于计算机中异或运算比加法运算快。而且这道题正好可以用异或的性质来解决。

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

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

class Solution {
public:
int missingNumber(vector<int>& nums) {
int n=nums.size();
int s=;
for(int i=;i<=n;i++){
s^=i;
}
int s2=nums[];
for(int i=;i<n;i++){
s2^=nums[i];
}
return s^s2;
}
};