美文网首页
[LeetCode]268. Missing Number

[LeetCode]268. Missing Number

作者: Eazow | 来源:发表于2016-06-03 14:36 被阅读111次

    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 <assert.h>
    
    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

          本文链接:https://www.haomeiwen.com/subject/ystldttx.html