天天看點

《leetCode》:Missing Number

題目

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

For example,
Given nums = [, , ] return 

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

思路

此題比較簡單。

0~n 累加求和 減去 array中所有數求和即為所求。

實作思路如下:

int missingNumber(int* nums, int numsSize) {
    if(nums==NULL||numsSize<){
        return -;
    }
    int arrSum=;
    int totalSum=;
    for(int i=;i<numsSize;i++){
        arrSum+=nums[i];
        totalSum+=(i+);
    }
    return totalSum-arrSum;
}