You are given an integer array nums, an integer array queries, and an integer x.
For each queries[i], you need to find the index of the queries[i]th
occurrence of x in the nums array. If there are fewer than queries[i]
occurrences of x, the answer should be -1 for that query.
Return an integer array answer containing the answers to all queries.
Input: nums =[1,3,1,7], queries =[1,3,2,4], x =1Output: [0,-1,2,-1]Explanation:
* For the 1st query, the first occurrence of 1is at index 0.* For the 2nd query, there are only two occurrences of 1in`nums`, so the answer is-1.* For the 3rd query, the second occurrence of 1is at index 2.* For the 4th query, there are only two occurrences of 1in`nums`, so the answer is-1.
The key idea is to first record all indices where x appears in nums. Then, for each query, we can directly check if the required occurrence exists and return its index, or -1 if it doesn’t. This avoids repeated scanning of the array for each query.
classSolution {
public List<Integer>occurrencesOfElement(int[] nums, int[] queries, int x) {
List<Integer> idxs =new ArrayList<>();
for (int i = 0; i < nums.length; i++)
if (nums[i]== x) idxs.add(i);
List<Integer> ans =new ArrayList<>();
for (int q : queries)
ans.add(q <= idxs.size() ? idxs.get(q-1) : -1);
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funoccurrencesOfElement(nums: IntArray, queries: IntArray, x: Int): List<Int> {
val idxs = mutableListOf<Int>()
for (i in nums.indices)
if (nums[i] == x) idxs.add(i)
return queries.map { if (it<= idxs.size) idxs[it-1] else -1 }
}
}
1
2
3
4
classSolution:
defoccurrencesOfElement(self, nums: list[int], queries: list[int], x: int) -> list[int]:
idxs = [i for i, v in enumerate(nums) if v == x]
return [idxs[q-1] if q <= len(idxs) else-1for q in queries]