Algorithm 以最有效的方式将几个预先排序的列表合并到一个联合列表中(并获取其中的顶部元素)
我有这样一个预设:Algorithm 以最有效的方式将几个预先排序的列表合并到一个联合列表中(并获取其中的顶部元素),algorithm,list,linked-list,Algorithm,List,Linked List,我有这样一个预设: 许多预先排序的列表,例如1000个元素,每个元素按一个标准排序(例如,基于时间的“最后一个”) 需要制作一个联合列表,该列表维护排序顺序,并且还包含1000个最后的元素(因此可以丢弃原始列表中不符合前1000名的元素)。 但是,也可以单独选择1000个顶部 合并需要尽可能快、尽可能高效。重新排序完整的合并列表不是一个选项 使用任何基于的数据结构: priority queue q = empty for each list add first element to q cr
- 许多预先排序的列表,例如1000个元素,每个元素按一个标准排序(例如,基于时间的“最后一个”)
- 需要制作一个联合列表,该列表维护排序顺序,并且还包含1000个最后的元素(因此可以丢弃原始列表中不符合前1000名的元素)。 但是,也可以单独选择1000个顶部
- 合并需要尽可能快、尽可能高效。重新排序完整的合并列表不是一个选项李>
priority queue q = empty
for each list add first element to q
create an array next that contains next elements for every list (initially next element is a second element)
while result list is not full
take top element from the q and add to the result list
add next element of the corresponding list to the q (if any)
update next element of the corresponding list
使用任何基于的数据结构:
priority queue q = empty
for each list add first element to q
create an array next that contains next elements for every list (initially next element is a second element)
while result list is not full
take top element from the q and add to the result list
add next element of the corresponding list to the q (if any)
update next element of the corresponding list
这个问题称为合并k排序数组。 在java中,解决它很简单。只需将元素添加到sortedSet(添加到sortedSet很快)。当你到达1000点时停下来
SortedSet<Integer> s = new TreeSet<>();
//s1,s2,s3 are the input lists here
int n = Math.max(Math.max(s2.size(), s1.size()), s3.size());
for (int i = 0; i < n || s.size() <= limit; i++) {
if (s1.get(i) != null) {
s.add(s1.get(i));
}
if (s2.get(i) != null) {
s.add(s2.get(i));
}
if (s3.get(i) != null) {
s.add(s3.get(i));
}
}
SortedSet s=新树集();
//s1、s2、s3是此处的输入列表
int n=Math.max(Math.max(s2.size()、s1.size()、s3.size());
对于(int i=0;i
SortedSet<Integer> s = new TreeSet<>();
//s1,s2,s3 are the input lists here
int n = Math.max(Math.max(s2.size(), s1.size()), s3.size());
for (int i = 0; i < n || s.size() <= limit; i++) {
if (s1.get(i) != null) {
s.add(s1.get(i));
}
if (s2.get(i) != null) {
s.add(s2.get(i));
}
if (s3.get(i) != null) {
s.add(s3.get(i));
}
}
SortedSet s=新树集();
//s1、s2、s3是此处的输入列表
int n=Math.max(Math.max(s2.size()、s1.size()、s3.size());
对于(int i=0;i