- 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。