close

題目

    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 相加,再減去陣列中的元素,剩下的數字,即為 missing number

code

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

arrow
arrow
    文章標籤
    C
    全站熱搜
    創作者介紹
    創作者 Davis 的頭像
    Davis

    Epoch

    Davis 發表在 痞客邦 留言(0) 人氣()