给定一个升序序列,问你target在序列中一个出现几次。
二分的变体,在经典的二分模板的arr[mid]等于target的时候左右都遍历一下把是target的加上去就行了,当然了,当前的这个值等于target,ans也要加一。
二分查找时间复杂度O(log n)。
class Solution:
"""
@param A: A an integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def binary_search(self, A, low, high, target, ans):
if low <= high:
mid = low + (high-low)//2
if A[mid]==target:
ans[0] += 1
tmp = mid
while(tmp-1>=0 and A[tmp-1]==target):
ans[0] += 1
tmp -= 1
tmp = mid
while(tmp+1<len(A) and A[tmp+1]==target):
ans[0] += 1
tmp += 1
return
elif target<A[mid]:
self.binary_search(A, low, mid-1, target, ans)
else:
self.binary_search(A, mid+1, high, target, ans)
def totalOccurrence(self, A, target):
# write your code here
ans = [0]
self.binary_search(A, 0, len(A)-1, target, ans)
return ans[0]