Missing Number

来源:互联网 发布:管家婆软件培训教程 编辑:程序博客网 时间:2024/06/04 18:17

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的数,每个都不一样,但是缺失了一个。让你找出这个数。

原理很简单,就是先把数组加上,然后0-n的和减去数组的和即为缺失的数。

同样也阔以异或操作,因为只有缺失的数没有成对。

int missingNumber(int* nums, int numsSize) {    if(nums == NULL || numsSize < 1)        return -1;    int miss = 0;    int max = 0;    for(int i = 0;i < numsSize;++i)    {        miss ^= nums[i];        if(nums[i] > max)            max = nums[i];    }    if(max + 1 == numsSize)    {        max = max + 1;    }    for(int i = 1;i <= max;++i)        miss ^= i;                    return miss;    }

 

0 0