Merge K sorted Array
跟Merge K sorted lists不同在于,从PQ里poll出来以后不知道下一个需要被加入PQ的是哪一个
所以需要写一个wrapper class
1 package fbPractise; 2 3 import java.util.*; 4 5 public class MergeKLists { 6 static class Pair { 7 int listIndex; 8 int idInList; 9 int value;10 public Pair(int l, int id, int val) {11 this.listIndex = l;12 this.idInList = id;13 this.value = val;14 }15 }16 17 public static Listmerge(List
> lists) {18 List res = new ArrayList ();19 20 Comparator comp = new Comparator () {21 public int compare(Pair p1, Pair p2) {22 return p1.value - p2.value;23 }24 };25 PriorityQueue pq = new PriorityQueue (1, comp);26 for (int i=0; i l1 = Arrays.asList(1,2,2,3,6);50 List l2 = Arrays.asList(1,4,5,7,8,9);51 List l3 = Arrays.asList(3,3,3,5,10);52 List
> lists = new ArrayList
>();53 lists.add(new ArrayList (l1));54 lists.add(new ArrayList (l2));55 lists.add(new ArrayList (l3));56 List res = merge(lists);57 System.out.println(res);58 }59 60 }