【LeetCode】Merge k Sorted Lists(java)

来源:互联网 发布:mac玩fifaonline3 编辑:程序博客网 时间:2024/05/17 17:57

我的方法就是暴力求解,时间复杂度为O(n2);

public class Solution {    public ListNode mergeKLists(ListNode[] lists) {        if(lists.length == 0)            return null;        ListNode result = new ListNode(-1),p = result;        int check = 0;        int[] checks = new int[lists.length];        while(check < lists.length){            int min = Integer.MAX_VALUE,index = -1;            for(int i = 0;i<lists.length;i++){                if(checks[i] == 0){                    if(lists[i]!= null){                        if(lists[i].val <min){                            min = lists[i].val;                            index = i;                        }                    }else{                        checks[i] = 1;                        check++;                    }                }            }            //System.out.println(index);            if(index != -1){                p.next = new ListNode(min);                p = p.next;                lists[index] = lists[index].next;            }        }        return result.next;    }}
使用优先队列不失为一种好方法

public class Solution {    public ListNode mergeKLists(ListNode[] lists) {        if (lists==null||lists.length==0) return null;        PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){            @Override            public int compare(ListNode o1,ListNode o2){                return o1.val -o2.val;            }        });                ListNode dummy = new ListNode(0);        ListNode tail=dummy;                for (ListNode node:lists)            if (node!=null)                queue.add(node);                    while (!queue.isEmpty()){            tail.next=queue.poll();            tail=tail.next;                        if (tail.next!=null)                queue.add(tail.next);        }        return dummy.next;    }}

2017/3/6


0 0
原创粉丝点击