#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
34:search for a Range
https://oj.leetcode.com/problems/search-for-a-range/
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O (log n).
If the target is not a found in the array, return [-1,-1].
For example,
Given [5, 7, 7, 8, 8, ten] and target value 8,
return [3, 4].
===comments by dabay===
Two-point lookup.
When Target is in the middle, expand toward both sides.
‘‘‘
Class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return A list of length 2, [Index1, Index2]
def searchrange (self, A, target):
def expend (Nums, index):
left = right = Index
While left-1 >= 0 and nums[left-1] = = Nums[index]:
Left-= 1
While right + 1 < len (nums) and Nums[right + 1] = = Nums[index]:
Right + = 1
return [left, right]
L, r = 0, Len (A)-1
While L <= r:
m = (L + r)/2
If a[m] = = target:
Return expend (A, M)
Elif A[m] < target:
L = m + 1
Else
r = M-1
Else
return [-1,-1]
def main ():
Sol = solution ()
Nums = [2,2]
target = 2
Print Sol.searchrange (nums, Target)
if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]34:search for a Range