LeetCode-Merge k Sorted Lists

来源:互联网 发布:ios 网络请求缓存 编辑:程序博客网 时间:2024/04/30 22:07

K路归并排序,将K路都放入最小堆构建起来,每次都取最小放入新的队列,然后将对应的队列再取一个放入堆中。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */class Solution {    public ListNode mergeKLists(ListNode[] lists) {      PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(10,new Comparator<ListNode>(){              @Override              public int compare(ListNode n1, ListNode n2)              {                  return n1.val-n2.val;              }          });      for(int i=0;i<lists.length;i++)      {          ListNode node = lists[i];           if(node!=null)          {              heap.offer(node);          }      }      ListNode head = null;      ListNode pre = head;      while(heap.size()>0)      {          ListNode cur = heap.poll();          if(head == null)          {              head = cur;              pre = head;          }          else          {              pre.next = cur;          }          pre = cur;          if(cur.next!=null)              heap.offer(cur.next);      }      return head;  }  }