题目:
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?
解题思路一:
将数组进行排序,然后循环判断,看看缺少的是哪一位,当都没有缺失的时候,说明是少了最后一位。代码:
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
nums.sort(compare);
var len = nums.length;
for(var i = 0; i < len; i++){
if(nums[i] != i){
return i;
}
}
return len;
};
function compare(value1, value2){
return value1 - value2;
}
解题思路二:
假设多一个长度的数组,[0, 1, 2, 。。。,len]的和与所求的数组的和进行相减,差值即是缺失值。代码:
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
var len = nums.length;
var sum = 0;
for(var i = 0; i < len; i++){
sum = sum + nums[i];
}
var sum1 = (len * (len+1))/2;
return sum1-sum;
};