题目:
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
代码:oj测试通过 Runtime: 91 ms
1 class Solution: 2 # @param A, a list of integers 3 # @param target, an integer to be searched 4 # @return a list of length 2, [index1, index2] 5 def searchAllTarget(self, A, index, target): 6 # left index 7 left_index = index 8 curr_index = index 9 while curr_index>=0 and A[curr_index]==target: 10 left_index = curr_index 11 curr_index = curr_index-1 12 # right index 13 right_index = index 14 curr_index = index 15 while curr_index<len(A) and A[curr_index]==target: 16 right_index = curr_index 17 curr_index = curr_index+1 18 return [left_index,right_index] 19 20 def searchRange(self, A, target): 21 # none case 22 if A is None: 23 return None 24 # short length cases 25 if len(A)==1 : 26 return[[-1,-1],[0,0]][A[0]==target] 27 # binary search 28 start = 0 29 end = len(A)-1 30 while start<=end : 31 if start==end: 32 if A[start]==target : 33 return self.searchAllTarget(A, start, target) 34 else : 35 return [-1,-1] 36 if start+1==end : 37 if A[start]==target : 38 return self.searchAllTarget(A, start, target) 39 elif A[end]==target : 40 return self.searchAllTarget(A, end, target) 41 else : 42 return [-1,-1] 43 mid = (start+end)/2 44 if A[mid]==target : 45 return self.searchAllTarget(A, mid, target) 46 elif A[mid]>target : 47 end = mid-1 48 else : 49 start = mid+1
思路:
这道题还是基于binary search,但是要求找到的是某个值的range。
分两步完成:
step1. 常规二分查找到target的某个index;如果没有找到则返回[-1,-1]
step2. 假设A中可能有多个位置为target,则从step1找到的index开始向左右search,直到把index左右两侧的target都找出来。
齐活儿
时间: 2024-10-14 08:17:54