2190. 数组中紧跟 key 之后出现最频繁的数字 - 力扣(LeetCode)
可以用一个哈希表(字典)来统计每个紧跟在 key
后面出现的数(target
)的次数。然后从这个哈希表中找出出现次数最多的那个 target
。
下面是对应的 Python 实现:
from collections import defaultdict
def most_frequent_target(nums, key):
count = defaultdict(int)
for i in range(len(nums) - 1):
if nums[i] == key:
count[nums[i + 1]] += 1
# 找到出现次数最多的 target
return max(count, key=count.get)
示例
nums = [1, 2, 2, 2, 3, 4, 2, 3]
key = 2
print(most_frequent_target(nums, key))
这个例子中,2 后面分别是 2、2、3、3,所以 target 为 2 出现了 2 次,target 为 3 也出现了 2 次。如果测试数据保证唯一最大值,那你会得到那个唯一的 target。