Merge K Sorted Arraylist
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 合并两个XX系列(基础+核心+高频题)
Page 1 of 1
Merge K Sorted Arraylist
static class ListContainer {
List<Integer> al;
int index;
public ListContainer(List<Integer> al, int index) {
this.al = al;
this.index = index;
}
}
static public List<Integer> mergeKList(List<List<Integer>> input) {
PriorityQueue<ListContainer> pq = new PriorityQueue<ListContainer>(input.size(), new Comparator<ListContainer>(){
public int compare(ListContainer a,ListContainer b){
return a.al.get(a.index)-b.al.get(b.index);
}
});
for (int i = 0; i < input.size(); i++)
pq.add(new ListContainer(input.get(i), 0));
List<Integer> res=new ArrayList<>();
while(!pq.isEmpty()){
ListContainer lc = pq.poll();
res.add(lc.al.get(lc.index));
if(lc.index < lc.al.size()-1)
pq.add(new ListContainer(lc.al, lc.index+1));
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> al1=new ArrayList<Integer>(Arrays.asList(0,3,6,9,12));
ArrayList<Integer> al2=new ArrayList<Integer>(Arrays.asList(2,4,8,10,14));
ArrayList<Integer> al3=new ArrayList<Integer>(Arrays.asList(1,5,7,11,13));
List<List<Integer>> input=new ArrayList<>();
input.add(al1);
input.add(al2);
input.add(al3);
List<Integer> res=mergeKList(input);
for(int i:res)
System.out.print(i+" ");
}
List<Integer> al;
int index;
public ListContainer(List<Integer> al, int index) {
this.al = al;
this.index = index;
}
}
static public List<Integer> mergeKList(List<List<Integer>> input) {
PriorityQueue<ListContainer> pq = new PriorityQueue<ListContainer>(input.size(), new Comparator<ListContainer>(){
public int compare(ListContainer a,ListContainer b){
return a.al.get(a.index)-b.al.get(b.index);
}
});
for (int i = 0; i < input.size(); i++)
pq.add(new ListContainer(input.get(i), 0));
List<Integer> res=new ArrayList<>();
while(!pq.isEmpty()){
ListContainer lc = pq.poll();
res.add(lc.al.get(lc.index));
if(lc.index < lc.al.size()-1)
pq.add(new ListContainer(lc.al, lc.index+1));
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> al1=new ArrayList<Integer>(Arrays.asList(0,3,6,9,12));
ArrayList<Integer> al2=new ArrayList<Integer>(Arrays.asList(2,4,8,10,14));
ArrayList<Integer> al3=new ArrayList<Integer>(Arrays.asList(1,5,7,11,13));
List<List<Integer>> input=new ArrayList<>();
input.add(al1);
input.add(al2);
input.add(al3);
List<Integer> res=mergeKList(input);
for(int i:res)
System.out.print(i+" ");
}
Similar topics
» Merge K Sorted Linkedlists
» Merge two sorted LinkedLists
» Merge Two Sorted Array
» Merge Two Sorted List
» Merge K Sorted Array
» Merge two sorted LinkedLists
» Merge Two Sorted Array
» Merge Two Sorted List
» Merge K Sorted Array
严氏北美IT公司面试真题汇总和解答论坛 :: LinkedIn公司面试真题: 注册用户可以看到隐藏题目:2017年下半年上机题,8 9 10三个月的onsite面试真题 :: 合并两个XX系列(基础+核心+高频题)
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|