统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
- 0 <= 数组长度 <= 50000
Python 解答:
class Solution:
def search(self, nums: List[int], target: int) -> int:
def findX(nums, left, right):
if left < right:
mid = (left+right)//2
if nums[mid] > target:
return findX(nums, left, mid)
elif nums[mid] < target:
return findX(nums, mid+1, right)
else:
return mid
elif nums[left] == target:
return left
else:
return -1
length = len(nums)
if not length:
return 0
index = findX(nums, 0, length-1)
if index == -1:
return 0
else:
count = 0
for i in range(index, -1, -1):
if nums[i] == target:
count += 1
else: break
for i in range(index+1, length):
if nums[i] == target:
count += 1
else: break
return count
留言