统计一个数字在排序数组中出现的次数。
示例1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
思路1: 暴力解法,顺序遍历数组。
代码如下:
class Solution:
def search(self, nums: List[int], target: int) -> int:
sum=0
n=len(nums)
for index in range(0,n):
if nums[index] == target:
sum = sum + 1
return sum
思路2: 题目中出现 “有序”,用二分查找。
class Solution:
def search(self, nums: List[int], target: int) -> int:
length = len(nums)
low = 0
high = length - 1
count = 0
if length == 0:
return 0
else:
while low <= high:
mid =int((low + high)/2)
if nums[mid] == target:
count = count +1
temp = mid +1
while temp < length and nums[temp] == target:
count = count +1
temp = temp + 1
temp = mid -1
while temp >=0 and nums[temp] == target:
count = count +1
temp = temp - 1
return count
elif nums[mid] < target:
low = mid +1
high = high
else:
high = mid - 1
low = low
if low > high:
return 0
注意:
1、边界问题
2、当nums[mid] == target
时,要考虑其前后可能都会出现等于target的情况。