本问题对应的 leetcode 原文链接:剑指 Offer 53 – II. 0~n-1中缺失的数字
问题描述
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。
示例1 :
输入: [0,1,3]
输出: 2
示例 2:
输入: [0,1,2,3,4,5,6,7,9]
输出: 8
限制:
- 1 <= 数组长度 <= 10000
解题思路
视频讲解直达: 本题视频讲解
代码实现
class Solution {
public int missingNumber(int[] nums) {
int l = 0, r = nums.length - 1;
while(l < r){
int mid = (r - l) / 2 + l;
if(nums[mid] == mid) l = mid + 1;
else r = mid;
}
return nums[l] == l ? l + 1 : l;
}
}
时间复杂度:log(n)
额外空间复杂度:O(1)
Python
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 0, len(nums) - 1
while l < r:
mid = (r - l) // 2 + l
if nums[mid] == mid:
l = mid + 1
else:
r = mid
return l + 1 if nums[l] == l else l
C++
class Solution {
public:
int missingNumber(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = (r - l) / 2 + l;
if (nums[mid] == mid) {
l = mid + 1;
} else {
r = mid;
}
}
return nums[l] == l ? l + 1 : l;
}
};
Go
func missingNumber(nums []int) int {
l, r := 0, len(nums) - 1
for l < r {
mid := (r - l) / 2 + l
if nums[mid] == mid {
l = mid + 1
} else {
r = mid
}
}
if nums[l] == l {
return l + 1
} else {
return l
}
}
JS
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
let l = 0,
r = nums.length - 1;
while (l < r) {
let mid = Math.floor((r - l) / 2 + l);
if (nums[mid] == mid) l = mid + 1;
else r = mid;
}
return nums[l] == l ? l + 1 : l;
};