LeetCode 题解工作台
查询带键的排列
给定一个正整数数组 queries ,其取值范围在 1 到 m 之间。 请你根据以下规则按顺序处理所有 queries[i] (从 i=0 到 i=queries.length-1 ): 首先,你有一个排列 P=[1,2,3,...,m] 。 对于当前的 i ,找到 queries[i] 在排列 P…
3
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·二分·indexed·树
答案摘要
题目数据规模不大,可以直接模拟。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·二分·indexed·树 题型思路
题目描述
给定一个正整数数组 queries ,其取值范围在 1 到 m 之间。 请你根据以下规则按顺序处理所有 queries[i](从 i=0 到 i=queries.length-1):
- 首先,你有一个排列
P=[1,2,3,...,m]。 - 对于当前的
i,找到queries[i]在排列P中的位置(从 0 开始索引),然后将它移到排列P的开头(即下标为 0 处)。注意,queries[i]的查询结果是queries[i]在P中移动前的位置。
返回一个数组,包含从给定 queries 中查询到的结果。
示例 1:
输入:queries = [3,1,2,1], m = 5 输出:[2,1,2,1] 解释:处理 queries 的过程如下: 对于 i=0: queries[i]=3, P=[1,2,3,4,5], 3 在 P 中的位置是 2,然后我们把 3 移动到 P 的开头,得到 P=[3,1,2,4,5] 。 对于 i=1: queries[i]=1, P=[3,1,2,4,5], 1 在 P 中的位置是 1,然后我们把 1 移动到 P 的开头,得到 P=[1,3,2,4,5] 。 对于 i=2: queries[i]=2, P=[1,3,2,4,5], 2 在 P 中的位置是 2,然后我们把 2 移动到 P 的开头,得到 P=[2,1,3,4,5] 。 对于 i=3: queries[i]=1, P=[2,1,3,4,5], 1 在 P 中的位置是 1,然后我们把 1 移动到 P 的开头,得到 P=[1,2,3,4,5] 。 因此,包含结果的数组为 [2,1,2,1] 。
示例 2:
输入:queries = [4,1,2,2], m = 4 输出:[3,1,2,0]
示例 3:
输入:queries = [7,5,5,8,3], m = 8 输出:[6,5,0,7,5]
提示:
1 <= m <= 10^31 <= queries.length <= m1 <= queries[i] <= m
解题思路
方法一:模拟
题目数据规模不大,可以直接模拟。
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
p = list(range(1, m + 1))
ans = []
for v in queries:
j = p.index(v)
ans.append(j)
p.pop(j)
p.insert(0, v)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate understands how to apply a Binary Indexed Tree for array manipulation and position tracking.
- question_mark
Assess how well the candidate can manage large inputs efficiently through optimized data structures.
- question_mark
Evaluate the candidate's approach to handling queries in constant space or time complexity.
常见陷阱
外企场景- error
Not using a Binary Indexed Tree or another efficient data structure could lead to a time complexity of O(n*m), which is inefficient for larger inputs.
- error
Failing to update the Binary Indexed Tree properly after each query will lead to incorrect results.
- error
Incorrectly handling edge cases where the queries involve the same element multiple times.
进阶变体
外企场景- arrow_right_alt
Instead of moving elements to the front, the problem could ask to move elements to the back of the array.
- arrow_right_alt
Queries could involve different types of operations such as adding or removing elements from the permutation dynamically.
- arrow_right_alt
The problem could be extended to handle range queries where multiple elements need to be processed at once.