面试题1. 在排序数组中查找数字
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
限制:
- 0 <= 数组长度 <= 50000
解题思路
- 一行代码解决,调用Python中的count函数
class Solution:
def search(self, nums: List[int], target: int) -> int:
return nums.count(target)
2. 利用键值对的思想来进行查找和统计数字次数
class Solution:
def search(self, nums: List[int], target: int) -> int:
data = dict()
for i in nums:
data[i] = data.get(i,0) + 1
result = 0
for (key,value) in data.items():
if key == target:
result = max(result,value)
return result