[LeetCode] Find Occurrences of an Element in an Array

3159. Find Occurrences of an Element in an Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> occurrencesOfElement(vector<int>& A, vector<int>& Q, int x) {
vector<int> at;
for(int i = 0; i < A.size(); i++) {
if(A[i] == x) at.push_back(i);
}
vector<int> res;
for(auto& q : Q) {
if(q > at.size()) res.push_back(-1);
else res.push_back(at[q-1]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/26/PS/LeetCode/find-occurrences-of-an-element-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.