题目描述

统计一个数字在排序数组中出现的次数。

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

分析

1.暴力

2.有序数组优先考虑二分查找

找到target在数组中的起始位置

解题

class Solution:
    
    def search(self, nums: List[int], target: int) -> int:
        #二分找边界
        if (target not in nums) or (not nums):
            return 0
        l, r = 0, len(nums)-1
        # nums.sort()
        while l<r:
            mid = (l+r)//2
            if nums[mid] > target:
                r = mid
            elif nums[mid] < target:
                l = mid+1
            else:
                while nums[l]< target:
                    l+=1
                while nums[r]> target:
                    r-=1
                break
        return r-l+1

 

相关文章:

  • 2021-12-21
  • 2021-10-21
  • 2022-12-23
  • 2021-09-20
  • 2021-09-11
  • 2022-02-10
  • 2021-09-28
猜你喜欢
  • 2021-07-29
  • 2021-10-04
  • 2022-12-23
  • 2021-06-13
  • 2021-08-23
  • 2021-12-13
  • 2021-10-04
相关资源
相似解决方案