Medium
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.
Example 1:
Input: nums = [1,3,1,7], queries = [1,3,2,4], x = 1
Output: [0,-1,2,-1]
Explanation:
nums
, so the answer is -1.nums
, so the answer is -1.Example 2:
Input: nums = [1,2,3], queries = [10], x = 5
Output: [-1]
Explanation:
nums
, so the answer is -1.Constraints:
1 <= nums.length, queries.length <= 105
1 <= queries[i] <= 105
1 <= nums[i], x <= 104
class Solution {
fun occurrencesOfElement(nums: IntArray, queries: IntArray, x: Int): IntArray {
val a = ArrayList<Int>()
run {
var i = 0
val l = nums.size
while (i < l) {
if (nums[i] == x) {
a.add(i)
}
i++
}
}
val l = queries.size
val r = IntArray(l)
for (i in 0 until l) {
r[i] = if (queries[i] > a.size) -1 else a[queries[i] - 1]
}
return r
}
}