LeetCode 题解工作台

查询数组中元素的出现位置

给你一个整数数组 nums ,一个整数数组 queries 和一个整数 x 。 对于每个查询 queries[i] ,你需要找到 nums 中第 queries[i] 个 x 的位置,并返回它的下标。如果数组中 x 的出现次数少于 queries[i] ,该查询的答案为 -1 。 请你返回一个整数数…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,我们可以先遍历一遍数组 ,找出所有值为 的元素的下标,记录在数组 中。 接着遍历数组 ,对于每个查询 ,如果 $i - 1$ 小于 的长度,那么答案就是 $\textit{ids}[i - 1]$,否则答案就是 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums ,一个整数数组 queries 和一个整数 x 。

对于每个查询 queries[i] ,你需要找到 nums 中第 queries[i] 个 x 的位置,并返回它的下标。如果数组中 x 的出现次数少于 queries[i] ,该查询的答案为 -1 。

请你返回一个整数数组 answer ,包含所有查询的答案。

 

示例 1:

输入:nums = [1,3,1,7], queries = [1,3,2,4], x = 1

输出:[0,-1,2,-1]

解释:

  • 第 1 个查询,第一个 1 出现在下标 0 处。
  • 第 2 个查询,nums 中只有两个 1 ,所以答案为 -1 。
  • 第 3 个查询,第二个 1 出现在下标 2 处。
  • 第 4 个查询,nums 中只有两个 1 ,所以答案为 -1 。

示例 2:

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

输出:[-1]

解释:

  • 第 1 个查询,nums 中没有 5 ,所以答案为 -1 。

 

提示:

  • 1 <= nums.length, queries.length <= 105
  • 1 <= queries[i] <= 105
  • 1 <= nums[i], x <= 104
lightbulb

解题思路

方法一:模拟

根据题目描述,我们可以先遍历一遍数组 nums\textit{nums},找出所有值为 xx 的元素的下标,记录在数组 ids\textit{ids} 中。

接着遍历数组 queries\textit{queries},对于每个查询 ii,如果 i1i - 1 小于 ids\textit{ids} 的长度,那么答案就是 ids[i1]\textit{ids}[i - 1],否则答案就是 1-1

时间复杂度 O(n+m)O(n + m),空间复杂度 O(n+m)O(n + m)。其中 nnmm 分别是数组 nums\textit{nums} 和数组 queries\textit{queries} 的长度。

1
2
3
4
5
6
7
class Solution:
    def occurrencesOfElement(
        self, nums: List[int], queries: List[int], x: int
    ) -> List[int]:
        ids = [i for i, v in enumerate(nums) if v == x]
        return [ids[i - 1] if i - 1 < len(ids) else -1 for i in queries]
speed

复杂度分析

指标
时间complexity is O(n + q) where n is nums length and q is queries length, because nums is scanned once and each query is answered in O(1). Space complexity is O(n) in the worst case for storing all occurrence indices of x.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if candidates precompute occurrence indices or scan nums repeatedly.

  • question_mark

    Listen for hash map usage versus naive iteration for multiple queries.

  • question_mark

    Notice if candidates handle edge cases when occurrences are fewer than query values.

warning

常见陷阱

外企场景
  • error

    Repeatedly scanning nums for each query causing TLE on large inputs.

  • error

    Not handling zero-based indexing properly for queries[i]th occurrence.

  • error

    Assuming every query is valid without checking if x occurs enough times.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count the number of occurrences instead of returning the index.

  • arrow_right_alt

    Return all indices for multiple target values in a single query array.

  • arrow_right_alt

    Find last k occurrences of x instead of the first k occurrences.

help

常见问题

外企场景

查询数组中元素的出现位置题解:数组·哈希·扫描 | LeetCode #3159 中等