268 - Missing Number

Problem

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Code

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int res = 0, i = 0;
        for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
            res = res ^ i ^ *it;
            i++;
        }
        return res ^ i;
    }
};

Link: https://leetcode.com/problems/missing-number/

上一篇:C# VSTO给Excel添加右键菜单并添加点击的click事件


下一篇:LeetCode刷题:268. Missing Number