题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
            //相当于分成两个有序链表,然后快慢指针
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
      return mergeList(lists,0,lists.size()-1);
    }
    public ListNode mergeList (ArrayList<ListNode> lists,int left,int right){
        if(left == right) return lists.get(left);
        if(left > right) return null;
        int mid = left+(right- left)/2;
        return merge(mergeList(lists,left,mid),mergeList(lists,mid+1,right)); 
    }
    //合并两个有序链表
    public ListNode merge(ListNode list1,ListNode list2){
        if(list1 == null)
           return list2;
        if(list2 == null)
           return list1;
        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;
        }
        //查看剩余序列,看哪个已经遍历完了
        if(list1 != null)
           cur.next = list1;
        if(list2 != null)
           cur.next = list2;
        return head.next;
    }    
}

全部评论

相关推荐

LastWh1spe...:ssob真有些人和那个没睡醒一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务