查询带键的排列
难度:
标签:
题目描述
代码结果
运行时间: 37 ms, 内存: 16.2 MB
/*
* In this Java Stream solution, we utilize streams to perform the transformation of the list P.
* We keep a list of queries as integers, then process each query to find its index in P and adjust the list accordingly.
*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamSolution {
public List<Integer> processQueries(List<Integer> queries, int m) {
List<Integer> P = new ArrayList<>();
for (int i = 1; i <= m; i++) {
P.add(i);
}
return queries.stream().map(query -> {
int index = P.indexOf(query); // Find index of query in P
P.remove(index); // Remove the element from its current position
P.add(0, query); // Add the element to the beginning
return index;
}).collect(Collectors.toList());
}
}
解释
方法:
此题解采用了树状数组(BIT)来高效地处理数组内元素的位置变动和查询。树状数组提供了两个关键操作:查询前缀和和更新元素,这使得我们可以在对数时间内查询任何元素的位置并更新。首先,初始化一个长度为 n+m 的树状数组,其中 n 是 queries 的长度,m 是排列 P 的长度。使用数组 pos 来记录排列 P 中每个元素的当前位置。初始时,P=[1,2,...,m] 并映射到树状数组的尾部,即 pos[1] = n+1, pos[2] = n+2,依此类推。处理 queries 时,对于每个查询 x,先通过 pos[x] 查询 x 在 P 中的位置,然后更新树状数组以反映 x 被移至数组前端的变化。这是通过减少当前位置的计数并在新位置(数组前端)增加计数来实现的。
时间复杂度:
O(n log(m+n))
空间复杂度:
O(m+n)
代码细节讲解
🦆
什么是树状数组(Binary Indexed Tree, BIT)以及它是如何在这种类型的问题中提供高效查询和更新操作的?
▷🦆
在题解中提到初始化树状数组的长度为 n+m,这里的 n 和 m 分别代表什么,它们为何要以这种方式组合?
▷🦆
题解中提到,初始化时将排列 P 中的元素映射到树状数组的尾部,这种映射策略的原因是什么?
▷🦆
在查询某个元素 x 位置之后立即更新树状数组将其移动到前端,具体是如何通过更新操作实现这一点的?
▷