《剑指offer》面试题38:数字在排序数组中出现的次数
数组已经排序,可以采用二分法!!!(排序数组的思路)
def NbrOfk(data,k):
start = get_first_k(data,k,0,len(data))
end = get_last_k(data,k,0,len(data))
if start is None or end is None:
return None
return end - start
def get_last_k(data,k,start,end):
if start >= end:
return None
while start < end:
mid = (start + end)//2
if data[mid] == k:
if mid == end - 1:
return end
elif data[mid + 1] != k:
return mid + 1
else:
start = mid + 1
elif k < data[mid]:
end = mid
else:
start = mid + 1
return None
def get_first_k(data,k,start,end):
if start >= end:
return None
while start < end:
mid = (start + end) // 2
if data[mid] == k:
if mid == 0:
return 0
elif data[mid - 1] != k:
return mid
else:
end = mid
elif k < data[mid]:
end = mid
else:
start = mid + 1
return None