合并K个排序链表和数据

合并K个排序链表

合并 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

时间复杂度是O(N * log K) N是结点总数,K是链表总数

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
import java.util.Queue;
import java.util.PriorityQueue;

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null || lists.length == 0) return null;
        Queue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>(){
            public int compare(ListNode l1, ListNode l2){
                return l1.val - l2.val;
            }
        });
        ListNode node = new ListNode(0);
        ListNode p = node;
        for(ListNode list : lists){
            if(list != null)
                queue.offer(list);
        }
        while(!queue.isEmpty()){
            p.next = queue.poll();
            p = p.next;
            if(p.next != null) queue.offer(p.next);
        }
        return node.next;
    }
}

 

合并K个排序数组

将 k 个有序数组合并为一个大的有序数组。

输入:
  [
    [1, 3, 5, 7],
    [2, 4, 6],
    [0, 8, 9, 10, 11]
  ]
输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

时间复杂度是O(N * log K) N是结点总数,K是链表总数

/**
 * 合并K个有序数组,时间复杂度是O(n * log k) n : 是数组里的总数, K : 是多少个数组
 * 时间复杂度为什么是O(n * log k),每个数组里的数加进堆里,堆的高度是logk, 所以每次加进堆的数的调整高度是logk,一共有n个数
 *
 */
public class Solution {
    class Element{
        public int row;
        public int col;
        public int val;
        public Element(int row, int col, int val){
            this.row = row;
            this.col = col;
            this.val = val;
        }
    }
    /**
     * @param arrays: k sorted integer arrays
     * @return: a sorted array
     */
    public int[] mergekSortedArrays(int[][] arrays) {
        // write your code here
        if(arrays == null) return new int[]{};
        int totalLen = 0;
        Queue<Element> queue = new PriorityQueue<>(new Comparator<Element>(){
            public int compare(Element e1, Element e2){
                return e1.val - e2.val;
            }
        }); 
        for(int i = 0; i < arrays.length; i++){
            if(arrays[i].length > 0){
                Element e = new Element(i, 0, arrays[i][0]);
                queue.add(e);
            }
            totalLen += arrays[i].length;
        }
        int[] arr = new int[totalLen];
        int index = 0;
        while(!queue.isEmpty()){
            Element el = queue.poll();
            arr[index++] = el.val;
            if(el.col + 1 < arrays[el.row].length){
                el.col += 1;
                el.val = arrays[el.row][el.col];
                queue.offer(el);
            }
        }
        return arr;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值