暴力解法可以做,这个题解给出另一种方法:二分法找左边界的思路
class Solution:
def search(self , nums: List[int], target: int) -> int:
# write code here
"""极端情况"""
if len(nums)==0: return 0
if len(nums)==1:
if nums[0]==target: return 1
else: return 0
if target>nums[-1]: return 0
if target<nums[0]: return 0
"""找target和正好比target大的数的左边界"""
l=self.getleft(nums, target)
r=self.getleft(nums, target+1)
return r-l
def getleft(self,data,k):
left,right=0,len(data)
while left<right:
mid=(left+right)//2
if data[mid]<k:left=mid+1
elif data[mid]>=k:right=mid
return left