Binary search
There is a template for binary search, by using which you do not need to think too much about the boundary and how to narrow down the interval / how to calculate mid value.
1 | // check null … |
Compared with normal binary search, the difference is that it cannot find the optimum value at while loop, instead, it sustains two possible value, and then check them after loop.
Some sample:
Find first number which is greater than or equals to the target value
http://www.lintcode.com/en/problem/search-insert-position/1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def searchInsert(self, A, target):
if A is None or len(A) == 0:
return 0
i = 0
j = len(A) - 1
while i + 1 < j:
mid = i + ((j - i) >> 1)
if A[mid] >= target:
j = mid
else:
i = mid
if A[i] >= target:
return i
elif A[j] >= target:
return j
return len(A)Find first bad version
Find the first value which is bad.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution:
"""
@param n: An integers.
@return: An integer which is the first bad version.
"""
def findFirstBadVersion(self, n):
i = 1
j = n
while i + 1 < j:
mid = i + ((j - i) >> 1)
if SVNRepo.isBadVersion(mid):
j = mid
else:
i = mid
if SVNRepo.isBadVersion(i):
return i
elif SVNRepo.isBadVersion(j):
return j
return -1Find the interval of a target value
http://www.lintcode.com/en/problem/search-for-a-range/(1) find the first value that equals to the target
(2) find the last value that equals to the target
1 | class Solution: |
- Find Minimum in Rotated Sorted Array
http://www.lintcode.com/en/problem/find-minimum-in-rotated-sorted-array-ii/
1 | class Solution: |
- Search in Rotated Sorted Array
http://www.lintcode.com/en/problem/search-in-rotated-sorted-array-ii/
1 | class Solution: |