zoukankan      html  css  js  c++  java
  • 0008 合并K个排序链表

    合并 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

    示例:

    输入:
    [
      1->4->5,
      1->3->4,
      2->6
    ]
    输出: 1->1->2->3->4->4->5->6
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode MergeKLists(ListNode[] lists) {
            ListNode res = new ListNode(0);
            ListNode p = res;
            List<ListNode> index = new List<ListNode>();
            for(int i=0; i<lists.Length; i++)
            {
                ListNode node = new ListNode(0);
                node.next = lists[i];
                index.Add(node);
            }
            while(index.Count != 0)
            {
                List<int> mins = new List<int>();
                int min = int.MaxValue;
                for(int i=index.Count-1; i>=0; i--)
                {
                    if(index[i].next != null)
                    {
                        if (index[i].next.val < min)
                        {
                            min = index[i].next.val;
                            mins.Clear();
                            mins.Add(i);
                        }
                        else if (index[i].next.val == min)
                        {
                            mins.Add(i);
                        }
                    }
                }
                for(int i=0; i<mins.Count; i++)
                {
                    ListNode node = new ListNode(index[mins[i]].next.val);
                    p.next = node;
                    p = node;
                    index[mins[i]] = index[mins[i]].next;
                }
                for(int i = index.Count - 1; i >= 0; i--)
                {
                    if(index[i].next == null)
                    {
                        index.Remove(index[i]);
                    }
                }
            }
            return res.next;
        }
    }
  • 相关阅读:
    django 模型层
    django 模板层
    django的视图层
    django-2的路由层(URLconf)
    django简介
    [Codeforces] 650A
    [codevs2916] 校门外的树2
    [Codevs 1690] 开关灯
    codevs3027线段覆盖2(DP)题解
    BC#65T4 ZYB's Tree
  • 原文地址:https://www.cnblogs.com/lvniao/p/9407370.html
Copyright © 2011-2022 走看看