天天看点

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