LeetCode-in-Java

3159. Find Occurrences of an Element in an Array

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:

Example 2:

Input: nums = [1,2,3], queries = [10], x = 5

Output: [-1]

Explanation:

Constraints:

Solution

import java.util.ArrayList;

public class Solution {
    public int[] occurrencesOfElement(int[] nums, int[] queries, int x) {
        ArrayList<Integer> a = new ArrayList<>();
        for (int i = 0, l = nums.length; i < l; i++) {
            if (nums[i] == x) {
                a.add(i);
            }
        }
        int l = queries.length;
        int[] r = new int[l];
        for (int i = 0; i < l; i++) {
            r[i] = queries[i] > a.size() ? -1 : a.get(queries[i] - 1);
        }
        return r;
    }
}