题目描述:
统计一个数字在排序数组中出现的次数
解法1:
思路:看到排序数组,首先想到的是二分法查找,先找到数字重复出现的左边位置,再找到右边位置,再相减即得到目标值
class Solution:
def GetNumberOfK(self, data, k):
left=0
right=len(data)-1
leftk=self.getleftK(data,k,left,right)
rightk=self.getrightK(data,k,left,right)
return rightk-leftk+1
def getleftK(self,data,k,left,right):
while left<=right:
middle=(left+right)//2
if data[middle]<k:
left=middle+1
else:
right=middle-1
return left
def getrightK(self,data,k,left,right):
while left<=right:
middle=(left+right)//2
if data[middle]<=k:
left=middle+1
else:
right=middle-1
return right
解法2:
class Solution:
def GetNumberOfK(self, data, k):
return data.count(k)
解法3:
class Solution:
def GetNumberOfK(self, data, k):
num=0
for i in data:
if i==k:
num+=1
return num