Missing Number

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;
    
}

 
發佈了68 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章