zoukankan      html  css  js  c++  java
  • LeetCode——Merge k Sorted Lists

    Discription:

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

    Subscribe to see which companies asked this question.

    思路:其实就是归并排序的最后一步归并操作。思想是递归分治,先把一个大问题分成2个子问题,然后对2个子问题的解进行合并。经过一次遍历就能找出已经有序的序列。就算是题目中给出的条件,已经有K个已经排好序的链表。然后递归的把问题分成2个,4个。。。。logK个子序列。然后每两个子序列的解进行合并。最后得到一个排好序的链表。时间复杂度为O(nlogK)。

    代码:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        public ListNode merge2Lists(ListNode list1, ListNode list2) {
            
            ListNode head = new ListNode(0);
            ListNode cur = head;
            
            while(list1 != null && list2 != null) {
                if(list1.val < list2.val) {
                    cur.next = list1;
                    list1 = list1.next;
                }
                else {
                    cur.next = list2;
                    list2 = list2.next;
                }
                cur = cur.next;
            }
            
            while(list1 != null) {
                cur.next = list1;
                list1 = list1.next;
                cur = cur.next;
            }
            
            while(list2 != null) {
                cur.next = list2;
                list2 = list2.next;
                cur = cur.next;
            }
            
            return head.next;
        }
        
        public ListNode mergeKLists(ListNode[] lists) {
            
            if(lists == null || lists.length == 0) {
                return null;
            }
            
            if(lists.length == 1) {
                return lists[0];
            }
            
            int mid = lists.length / 2;
            
            ListNode list1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid));
            ListNode list2 = mergeKLists(Arrays.copyOfRange(lists, mid, lists.length));
            
    
            return merge2Lists(list1, list2);
        }
    }

    为何这道题Java的效率这么高,把C/C++都完爆了。

  • 相关阅读:
    A+B
    Java(2)数据类型转换、变量和常量
    1002. 写出这个数 (20)
    1001.害死人不偿命的(3n+1)
    ACM算法目录
    《mysql必知必会》学习_第19章
    Redhat 6.1安装ArcGIS Server10.1
    ArcGIS 10.1 for Server安装教程系列—— Linux下的单机安装
    ArcGIS 10.1 for Server安装教程系列—— Linux下的单机安装
    Linux ANSI 乱码问题
  • 原文地址:https://www.cnblogs.com/wxisme/p/4953188.html
Copyright © 2011-2022 走看看