链接: 原文链接.
class Solution: # 自己写的解法,直接遍历 def search(self, nums: List[int], target: int) -> int: # nums、target count = 0 for i in nums: if target == i: count += 1 return count # 大佬的写法,二分查找 # 不是特别理解. # class Solution: # def search(self, nums: [int], target: int) -> int: # # 搜索右边界 right # i, j = 0, len(nums) - 1 # while i <= j: # m = (i + j) // 2 # if nums[m] <= target: i = m + 1 # else: j = m - 1 # right = i # # 若数组中无 target ,则提前返回 # if j >= 0 and nums[j] != target: return 0 # # 搜索左边界 left # i = 0 # while i <= j: # m = (i + j) // 2 # if nums[m] < target: i = m + 1 # else: j = m - 1 # left = j # return right - left - 1 # class Solution: # def search(self, nums: [int], target: int) -> int: # def helper(tar): # i, j = 0, len(nums) - 1 # while i <= j: # m = (i + j) // 2 # if nums[m] <= tar: i = m + 1 # else: j = m - 1 # return i # return helper(target) - helper(target - 1)