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 elementm, then
m - 1is the missing number. The solution is a modified version of binary search. Note that when update the
rightpointer, it should be updated to
midpointer, 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
相关文章推荐
- Given an array say [9,20,-2,-45,23,5,1], find the minimum positive missing number from the array.
- Find the missing element in a given permutation.
- InnoDB: The log sequence number in ibdata files does not match
- 1. MissingInteger 最小遗失整数 Find the minimal positive integer not occurring in a given sequence.
- O(n lg n)-time Algorithm to Find the Longest Monotonically Increasing Sub-sequence
- C/C++ Find the missing number
- Problem 14 - Find the longest sequence using a starting number under one million.
- Find the smallest positive number missing from an unsorted array
- 1. 少了一个PermMissingElem Find the missing element in a given permutation.
- Find a number in the array having least difference with the given number (n)
- LintCode --find-the-missing-number(寻找缺失的数)
- Find missing number in a sorted array
- Array(11) -- Largest Rectangle in Histogram, Maximal Rectangle, Find the Duplicate Number
- Given a number,find the next higher number using the same digits in the number.
- Data Structure Array: Find the Missing Number
- InnoDB: The log sequence number in ibdata files does not match
- 一道面试题Lintcode196-Find the Missing Number
- lintcode Find the Missing Number II
- Lintcode196 Find the Missing Number solution 题解
- *[Lintcode]Find the Missing Number