统计一个数字在排序数组中出现的次数。
来自牛客大神的思路:https://www.nowcoder.com/questionTerminal/70610bf967994b22bb1c26f9ae901fa2
简单来说,由于数组是排序数组,而且都是整数。因此不用查找k的左右位置,只需要找到k-0.5和k+0.5的插入位置,然后左右相减即可。既然是排序数组,那么就可以用二分法查找。
# -*- coding:utf-8 -*-
class Solution:
def search(self,data,num):
left = 0
right = len(data)-1
while left <= right:
mid = (left+right)//2
if data[mid] > num:
right = mid -1
else:
left = mid + 1
return right # 注意这里是返回right,不是mid,因为data中没有num
def GetNumberOfK(self, data, k):
# write code here
if data == None:
return 0
else:
return self.search(data,k+0.5) - self.search(data,k-0.5)
直接找k出现的最左边,和最右边的位置,然后相减。仍然是二分查找k。
# -*- coding:utf-8 -*-
class Solution:
def getleft(self,data,k,left,right):
while left <= right:
mid = (left + right) //2
if data[mid] >= k:
# 注意,传统的二分法没有等号,如果相等了,就直接返回mid了,但是这个有点特殊
right = mid -1
else:
left = mid +1
return left
# 找data中最后一次出现k的下标
def getright(self,data,k,left,right):
while left <= right:
mid = (left + right) //2
if data[mid] > k:
right = mid -1
else: # 注意
left = mid +1
return right
def GetNumberOfK(self, data, k):
# write code here
left = 0
right = len(data)-1
rightk = self.getright(data,k,left,right)
leftk = self.getleft(data,k,left,right)
return rightk - leftk + 1