严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Merge K Sorted Arraylist

Go down

Merge K Sorted Arraylist Empty Merge K Sorted Arraylist

Post by Admin Sat Oct 21, 2017 4:51 pm

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+" ");

}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum