(LeetCode) 268. Missing Number

来源:互联网 发布:社交网络 百度云盘 编辑:程序博客网 时间:2024/06/06 16:33

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.

268. 遗漏数字

给定一个数组,包含n个不一样的数字,0, 1, 2, ..., n,找出其中漏掉的数字。
比如:给出 nums = [0, 1, 3] 返回 2.

思路

使用异或操作,将数组与0-n无缺失数据进行异或,得到的就是遗漏的数字。

代码

class Solution {public:    int missingNumber(vector<int>& nums) {        int n = nums.size(), res=0;        for (int i=0; i<n; i++){            res ^= nums[i]^i;        }        return res^n;    }};
0 0
原创粉丝点击