原题网址: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;
}
}

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

被折叠的 条评论
为什么被折叠?



