使用二分
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
count = 0
if len(data)==0:
return 0
index = self.binaryquery(data,k)
if index == -1:
return 0
cur = index
while cur < len(data) and data[cur]==k:
count += 1
cur += 1
cur = index
while cur >= 0 and data[cur]==k:
count += 1
cur -= 1
return count-1
def binaryquery(self,data,k):
l = len(data)
m = l//2
a = -1
b = -1
if m==0 and data[m] != k:
return -1
if data[m] == k:
return m
elif k > data[m]:
a = self.binaryquery(data[:m:-1],k)
else:
b = self.binaryquery(data[:m],k)
if a>b:
return a
else:
return b