[LeetCode][JavaScript]Missing Number
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?
https://leetcode.com/problems/missing-number/
求出序列中缺少的那个数,序列肯定是乱序的。
把0到n的数相加(等差数列求和),再一个个减掉,最后剩下的就是结果。
本来以为相加可能超过了长度限制,要用大数加减法,试了一下并不用。
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var missingNumber = function(nums) { 6 var i, res = 0; 7 res = parseInt((nums.length + 1) * nums.length / 2); 8 for(i = 0; i < nums.length; i++){ 9 res -= nums[i]; 10 } 11 return res; 12 };