数组_数字在排序数组中出现的次数
思路:两次二分法,分别找到数字k在数组的首尾位置。
二分方参考https://www.cnblogs.com/yupeng/p/3418293.html
法一:
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if len(data)==0:
return 0
left = self.get_left(data, k)
right = self.get_right(data, k)
return right-left+1
def get_left(self, data, k):
left = 0
right = len(data)-1
while left <= right:
mid = (left+right)//2
if data[mid] >= k:
right = mid-1
else:
left = mid+1
return left
def get_right(self, data, k):
left = 0
right = len(data)-1
while left <= right:
mid = (left+right)//2
if data[mid] > k:
right = mid-1
else:
left = mid+1
return right
法2:
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if len(data)<1:
return 0
left = 0
right = len(data)-1
mid = (left+right)//2
if data[mid]==k:
left = mid
right = mid
while left>0:
if data[left-1]==k:
left -= 1
else:
break
while right<len(data)-1:
if data[right+1]==k:
right += 1
else:
break
return right - left + 1
elif data[mid] > k:
return self.GetNumberOfK(data[:mid], k)
else:
return self.GetNumberOfK(data[mid+1:], k)