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?

思路

  1. 缺少的數(shù) == sum(0.....n) - sum(num[i])
  2. 有可能input的數(shù)組很大,直接計(jì)算sum會超過integer的范圍,所以一邊加i一邊減去nums[i]。最后剩下的數(shù)就是missing number
class Solution {
    public int missingNumber(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        
        int add = 0;
        int result = nums.length;
        for (int i = 0; i < nums.length; i++) {
            //add += i;
            result = result + (i - nums[i]);
        }
        
        return result;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容