Problem Statement
Given an increasing sequence of numbers from 1 to n with only one missing number, how can you find that missing number without traversing the sequence in linear fashion. In other words, time complexity of your algorithm must be less than O(n)?
Algorithm: Binary Search
二分查找算法: 二分查找算法是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜 素过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组 为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。折半搜索每次把搜索区域减少一半,时间复杂度为Ο(logn) 。
Solution
Find the first misplaced element m
, then m - 1
is the missing number. The solution is a modified version of binary search. Note that when update the right
pointer, it should be updated to mid
pointer, instead of mid - 1
.
def missing_element(nums, n):
"""Find the missing number.
Time Complexity: O(logn)
"""
if n == 1:
return 0
left, right = 0, n - 2
while left < right:
mid = (left + right) >> 1
if mid == nums[mid] - 1:
left = mid + 1
else:
right = mid
return nums[left] - 1