您的位置:首页 > 产品设计 > UI/UE

PIQ59: Find the missing number in the increasing sequence

2016-08-23 12:51 429 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分搜索 数组