题目描述
blablabla
样例
class Solution(object):
def getNumberOfK(self, nums, k):
"""
:type nums: list[int]
:type k: int
:rtype: int
"""
if len(nums) <= 0:
return 0
if len(nums) == 1:
return 1 if nums[0] == k else 0
# 二分搜索
left, right = 0, len(nums) - 1
while right > left + 1:
mid = left + (right - left) // 2
if nums[mid] >= k:
right = mid
else:
left = mid
if nums[right] == k:
mid = right
if nums[left] == k:
mid = left
# 得到mid
if nums[mid] == k:
count = 0
left, right = mid, mid
while left >= 0 and nums[left] == k:
count += 1
left -= 1
while right < len(nums) and nums[right] == k:
count += 1
right += 1
return count - 1
else:
return 0