题目
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
思路
- 循环遍历
直接 for 遍历 - 双指针遍历
利用二分查找,i,j 寻找左右边界,右边界 - 左边界 - 1 就是个数
程序
- 循环遍历
class Solution:
def search(self, nums: List[int], target: int) -> int:
sum = 0
for i in nums:
if i == tar:
sum += 1
return sum
- 双指针
class Solution:
def search(self, nums: List[int], target: int) -> int:
i,j = 0, len(nums) - 1
while i <= j:
mid = (i+j) // 2
if nums[mid] <= target:
i = mid +1
else:
j = mid - 1
right = i
if j>=0 and nums[j]!=target : return 0
i = 0
while i <= j:
mid = (i+j) // 2
if nums[mid] < target:
i = mid + 1
else:
j = mid - 1
left = j
return right - left -1