23. Merge k Sorted Lists

JJ·2021년 2월 7일
0

Algorithms

목록 보기
97/114
class Solution {
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i < nums.length; i++) {
            int cur = nums[i];
            int count = 0;
            for (int j = i; j < nums.length; j++) {
                if (nums[j] < cur) {
                    count++;
                }
            }
            result.add(count);
        }
        
        return result;
    }
}

2중 for 문이와 함께 TIME LIMIT으로 힘차게 시작했읍니다^^

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        Comparator<ListNode> comp;
        comp = new Comparator<ListNode>() {
            @Override
            public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }
        };
        
        Queue<ListNode> q = new PriorityQueue<ListNode>(comp);
        
        for (ListNode l : lists) {
            if (l != null) {
                q.add(l);
            }
        }
        
        ListNode head = new ListNode(0);
        
        ListNode point = head;
        
        while (! q.isEmpty()) {
            point.next = q.poll();
            point = point.next;
            ListNode next = point.next;
            if (next != null) {
                q.add(next);
            }
        }
        
        return head.next;
    }
}

Runtime: 4 ms, faster than 80.34% of Java online submissions for Merge k Sorted Lists.
Memory Usage: 40.7 MB, less than 61.79% of Java online submissions for Merge k Sorted Lists.

0개의 댓글