序列顺序查询
难度:
标签:
题目描述
代码结果
运行时间: 473 ms, 内存: 38.7 MB
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
// Class to represent a point of interest with a name and score
class Point {
String name;
int score;
public Point(String name, int score) {
this.name = name;
this.score = score;
}
}
// Main class to handle the addition of points and retrieval of the i-th best point using streams
public class SORTracker {
private List<Point> points;
private int queryCount;
public SORTracker() {
points = new ArrayList<>();
queryCount = 0;
}
// Adds a new point with a name and score to the tracker
public void add(String name, int score) {
Point newPoint = new Point(name, score);
points.add(newPoint);
}
// Retrieves the i-th best point (where i is the current query count) using streams
public String get() {
queryCount++;
return points.stream()
.sorted(Comparator.comparing(Point::getScore).reversed().thenComparing(Point::getName))
.map(Point::getName)
.collect(Collectors.toList())
.get(queryCount - 1);
}
}
解释
方法:
此题解利用了sortedcontainers库中的SortedList数据结构,以维持景点的有序状态。每个景点以元组(-score, name)的形式存储,这样可以确保景点在列表中自动按照评分降序和字典序升序排列。添加操作直接将景点元组插入SortedList,由于SortedList内部机制,插入后列表仍然保持有序。查询操作则根据累积的查询次数n(self.n),从SortedList中获取第n好的景点。
时间复杂度:
add: O(log n), get: O(1)
空间复杂度:
O(n)
代码细节讲解
🦆
SortedList数据结构在插入和查询操作中的时间复杂度是多少?
▷🦆
SortedList是如何确保在元组(-score, name)中,评分相同的情况下能自动按字典序排序?
▷🦆
为什么要选择使用SortedList而不是其他数据结构如优先队列或平衡二叉搜索树?
▷