LeetCode 23. Merge k Sorted Lists(K路合并)

本文介绍了一种使用最小堆的方法来解决LeetCode上的合并K个有序链表问题。通过自定义实现最小堆操作,如插入、删除最小元素等,有效地将多个有序链表合并为一个有序链表。

原题网址:https://leetcode.com/problems/merge-k-sorted-lists/

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

方法:使用最小堆维护当前最小值。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ListNode[] heap;
    private int size = 0;
    private void offer(ListNode node) {
        int pos = size;
        heap[size++] = node;
        int up = (pos-1) >> 1;
        while (pos > 0 && heap[pos].val < heap[up].val) {
            ListNode temp = heap[pos];
            heap[pos] = heap[up];
            heap[up] = temp;
            pos = up;
            up = (pos-1) >> 1;            
        }
    } 
    /*
    注意,出堆的时候必须将堆底的元素放到堆顶,不然会出错!!!!!
    */
    private ListNode poll() {
        ListNode polled = heap[0];
        replace(heap[--size]);
        return polled;
    }
    private void replace(ListNode node) {
        heap[0] = node;
        int pos = 0;
        int bottom = (pos<<1) + 1;
        while (bottom<size) {
            int min = bottom;
            if (bottom+1<size && heap[bottom+1].val<heap[bottom].val) min = bottom+1;
            if (heap[pos].val <= heap[min].val) break;
            ListNode temp = heap[pos];
            heap[pos] = heap[min];
            heap[min] = temp;
            pos = min;
            bottom = (pos<<1) + 1;
        }
    }
    private ListNode peek() {
        if (size == 0) return null;
        return heap[0];
    }
    public ListNode mergeKLists(ListNode[] lists) {
        heap = new ListNode[lists.length];
        for(int i=0; i<lists.length; i++) if (lists[i] != null) offer(lists[i]);
        ListNode merged = new ListNode(0);
        ListNode tail = merged;
        while (size > 0) {
            ListNode node = peek();
            if (node.next != null) replace(node.next); else poll();
            tail.next = node;
            tail = tail.next;
            tail.next = null;
        }
        return merged.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值