您的位置:首页 > 编程语言 > Java开发

leetcode:Merge k Sorted Lists 【Java】

2016-03-03 17:31 633 查看
一、问题描述

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

二、问题分析

利用分治法,并结合算法Merge
Two Sorted Lists

三、算法代码

public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0){
            return null;
        }
        return Sort(lists, 0, lists.length - 1);
    }
    
    public ListNode Sort(ListNode[] lists, int low, int high) {//利用分治思想排序
        if (low < high) {
            int mid = low + (high - low) / 2;
            ListNode head1 = Sort(lists, low, mid);
            ListNode head2 = Sort(lists, mid + 1, high);
            return mergeTwoLists(head1, head2);
        } else
            return lists[low];
    }
    
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        ListNode l1_index = l1;
        ListNode l2_index = l2;
        while(l1_index != null && l2_index != null){
            if(l1_index.val >= l2_index.val){
                cur.next = l2_index;//保持合并后的链表也是从小到大的顺序
                cur = cur.next;
                l2_index = l2_index.next;
            }else{
                cur.next = l1_index;
                cur = cur.next;
                l1_index = l1_index.next;
            }
        }
        
        if(l1_index != null){
            cur.next = l1_index;
        }
        
        if(l2_index != null){
            cur.next = l2_index;
        }
        
        return head.next;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: