《leetCode》: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 累加求和 减去 array中所有数求和即为所求。

实现思路如下:

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

你可能感兴趣的:(LeetCode,算法,Missing,Numbers)