题目:
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。
/** * @param {number[]} nums * @return {number} */ var missingNumber = function(nums) { if(nums.length==0){ return; } nums.sort(function(a,b){return a-b;}); var l=0,r=nums.length-1,middle=0; while(l<r){ middle=l+Math.floor((r-l)/2); if(middle!=nums[middle]){ r=middle-1; } if(middle==nums[middle]){ l=middle+1; } } return nums[l]==l?nums[l]+1:l };