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

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

    第一遍:

     1 public class Solution {
     2     public ListNode mergeKLists(ArrayList<ListNode> lists) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(lists.size()==0) return null;
     6         ListNode header = new ListNode(-1), cur = header;
     7         // boolean sig = true;
     8         while(true){
     9             int pos = -1;
    10             for(int i = 0; i < lists.size(); i ++){
    11                 if(lists.get(i) != null && (pos == -1 || lists.get(i).val < lists.get(pos).val))
    12                     pos = i;
    13             }
    14             if(pos != -1){
    15                 cur.next = lists.get(pos);
    16                 cur = cur.next;
    17                 lists.set(pos,lists.get(pos).next);
    18 
    19             }else{
    20                 break;
    21             }
    22         }
    23         return header.next;
    24     }
    25 }

    第三遍:

    去掉 null的项 可以加速 查找。

     1 public class Solution {
     2     public ListNode mergeKLists(ArrayList<ListNode> lists) {
     3         ListNode header = new ListNode(-1);
     4         ListNode cur = header;
     5         if(lists == null || lists.size() == 0) return null;
     6         while(true){
     7             int min = -1;
     8             for(int i = 0; i < lists.size(); i ++){
     9                 if(lists.get(i) == null){
    10                     lists.remove(i);
    11                     i --;
    12                 }
    13                 else if(min == -1 || lists.get(i).val < lists.get(min).val)
    14                     min = i;
    15             }
    16             if(min == -1) break;
    17             else{
    18                 cur.next = lists.get(min);
    19                 lists.set(min,lists.get(min).next);
    20                 cur = cur.next;
    21             }
    22         }
    23         return header.next;
    24     }
    25 }
  • 相关阅读:
    python-局部变量与全局变量作用域
    python-函数(上):函数返回值、函数调用、前向引用
    python-文件读写
    python-输入和输出
    python-模块介绍及os模块的方法
    python-continue和break的区别
    python-for循环
    python-while循环
    python-三元运算和if...else
    python-数据类型(下) :byte、列表、元组、集合
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3893919.html
Copyright © 2011-2022 走看看