[LeetCode]268. 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个数,它们的和sum是确定的,那么用sum减去给定n个数的和就求出了missing的那个数

c代码
#include 

int missingNumber(int* nums, int numsSize) {
    int expectedSum = (1+numsSize)*numsSize/2;
    int i = 0;
    int sum = 0;
    for(i = 0; i < numsSize; i++) {
        sum += nums[i];
    }
    return expectedSum - sum;
}

int main() {
    int nums[3] = {0, 1, 3};
    assert(missingNumber(nums, 3) == 2);

    return 0;
}

你可能感兴趣的:([LeetCode]268. Missing Number)