有序链表多路归并

有序链表多路归并

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

    Example:

    Input:
    [
    1->4->5,
    1->3->4,
    2->6
    ]
    Output: 1->1->2->3->4->4->5->6

这个是LeetCode的23题,对k个有序链表进行多路归并,整体思路是遍历ListNode数组,找到所有数组节点中头元素中最小的那个节点,然后将next指向这个元素,通过Set来标记已经遍历完的ListNode节点,下面是Java代码实现:

import java.util.HashSet;
import java.util.Set;

/**
 * Created by CvShrimp on 2019/8/26
 */
public class MergeMultiSortedLists {

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

    public ListNode mergeKLists(ListNode[] lists) {
        if(lists == null) {
            return null;
        }
        int length = lists.length;

        ListNode head = new ListNode(0);
        ListNode sortedNode = head;
        // 保存已经完结的ListNode
        Set endSet = new HashSet<>();
        // 当不是所有ListNode都已经完结时,一直遍历
        while(endSet.size() < length) {
            ListNode minNode = null;
            int min = Integer.MAX_VALUE;
            int minIndex = 0;
            boolean enter = false;
            for(int i = 0; i < length; i++) {
                // 如果当前ListNode已经遍历完
                if(lists[i] == null) {
                    // 如果是第一次遍历完,加入set
                    if(!endSet.contains(i)) {
                        endSet.add(i);
                    }
                    continue;
                }
                int val = lists[i].val;
                if(val < min) {
                    enter = true;
                    minIndex = i;
                    min = val;
                    minNode = lists[i];
                }
            }
            if(enter) {
                lists[minIndex] = lists[minIndex].next;
                sortedNode.next = minNode;
                sortedNode = sortedNode.next;
            }

        }
        return head.next;
    }

}

你可能感兴趣的:(Algorithms)