题目
某班级考试成绩按非严格递增顺序记录于整数数组
scores
,请返回目标成绩target
的出现次数。
解题
def countOccurrences(scores, target):
# 查找 target 在数组中第一次出现的位置
def findFirstPosition(scores, target):
left, right = 0, len(scores) - 1
while left <= right:
mid = (left + right) // 2
if scores[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
# 查找 target 在数组中最后一次出现的位置
def findLastPosition(scores, target):
left, right = 0, len(scores) - 1
while left <= right:
mid = (left + right) // 2
if scores[mid] <= target:
left = mid + 1
else:
right = mid - 1
return right
first_position = findFirstPosition(scores, target)
last_position = findLastPosition(scores, target)
# 如果目标成绩不存在于数组中,返回 0
if first_position <= last_position:
return last_position - first_position + 1
else:
return 0
# 示例使用
scores = [2, 2, 3, 4, 4, 4, 5, 6, 6, 8]
target = 4
print(countOccurrences(scores, target)) # 输出: 3