23. Merge k Sorted Lists

来源:互联网 发布:淘宝助理宝贝图片尺寸 编辑:程序博客网 时间:2024/06/05 03:35

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; } * } */class Solution {    public ListNode mergeKLists(ListNode[] lists) {        if (lists.length == 0)return null;return help(lists, 0, lists.length - 1);    }        public ListNode help(ListNode[] lists, int left, int right) {if (left == right)return lists[left];int center = left + (right - left) / 2;return merge(help(lists, left, center), help(lists, center + 1, right));}        public ListNode merge(ListNode l1, ListNode l2) {ListNode head = new ListNode(0);ListNode re = head;while (l1 != null || l2 != null) {if (l1 != null && l2 != null) {if (l1.val < l2.val) {head.next = l1;head = head.next;l1 = l1.next;} else {head.next = l2;head = head.next;l2 = l2.next;}} else if (l1 != null) {head.next = l1;head = head.next;l1 = l1.next;} else {head.next = l2;head = head.next;l2 = l2.next;}}return re.next;}}