- Leetcode 3159. Find Occurrences of an Element in an Array
- 1. 解题思路
- 2. 代码实现
- 题目链接:3159. Find Occurrences of an Element in an Array
1. 解题思路
这一题的话我们只需要首先统计一下array当中目标元素x出现在第几次的位置,构造一个hash table,然后对于每一个query进行查询即可。
2. 代码实现
给出python代码实现如下:
class Solution:def occurrencesOfElement(self, nums: List[int], queries: List[int], x: int) -> List[int]:answers = {}cnt = 0for i, num in enumerate(nums):if num == x:cnt += 1answers[cnt] = ians = [answers[q] if q in answers else -1 for q in queries]return ans
提交代码评测得到:耗时1220ms,占用内存33.7MB。