leetcode——23. 合并K个排序链表

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        if not lists:
            return 
        #暴力法
        r=[]
        for i in range(len(lists)):
            if not lists[i]:
                continue
            head=lists[i]
            p=head
            while p:
                r.append(p.val)
                p=p.next
        if not r:
            return
        r.sort()
        head=ListNode(r[0])
        p=head
        for j in range(1,len(r)):
            p.next=ListNode(r[j])
            p=p.next
        return head
执行用时 :76 ms, 在所有 python 提交中击败了99.27%的用户
内存消耗 :20 MB, 在所有 python 提交中击败了18.16%的用户
 
——2019.10.31
 

public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length == 0){
            return null;
        }else if(lists.length == 1){
            return lists[0];
        }
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0;i<lists.length;i++){
            ListNode node = lists[i];
            while(node != null){
                list.add(node.val);
                node = node.next;
            }
        }
        System.out.println(list);
        int[] a = list.stream().mapToInt(Integer::valueOf).toArray();
        Arrays.sort(a);
        if(a.length == 0){
            return null;
        }
        ListNode node = new ListNode(a[0]);
        ListNode head = node;
        for(int i = 1;i<a.length;i++){
            node.next = new ListNode(a[i]);
            node = node.next;
        }
        return head;
    }

 

 ——2020.7.5

posted @ 2019-10-31 20:29  欣姐姐  阅读(110)  评论(0编辑  收藏  举报