python 代码
class Solution(object):
def getNumberOfK(self, nums, k):
"""
:type nums: list[int]
:type k: int
:rtype: int
"""
if not nums: return 0
l = 0
r = len(nums) - 1
while l < r:
mid = (l+r) >> 1
if nums[mid] >= k:
r = mid
else:
l = mid + 1
s1 = l
l = 0
r = len(nums) - 1
while l < r:
mid = (l+r+1) >> 1
if nums[mid] <= k:
l = mid
else:
r = mid - 1
s2 = l
return s2-s1+1 if nums[s1]==k and nums[s2]==k else 0