简体   繁体   中英

How to sort 2 unsorted lists and create a sorted list?

I was given a two arraylists which were unsorted and have a single sorted list. I was not allowed to sort the first two lists.

I just dumped both lists in the priority queue and pulled the values out and put it into the third list. Like..

public static void sortList() {
        ArrayList<Integer> l1 = new ArrayList<>();
        l1.add(10);
        l1.add(11);
        l1.add(8);
        l1.add(15);
        l1.add(2);

        ArrayList<Integer> l2 = new ArrayList<>();
        l2.add(11);
        l2.add(2);
        l2.add(15);
        l2.add(18);

        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int i = 0; i < l1.size(); i++) {
            queue.add(l1.get(i));
        }

        for (int i = 0; i < l2.size(); i++) {
            queue.add(l2.get(i));
        }

        ArrayList<Integer> list3 = new ArrayList<>();

        while (!queue.isEmpty()) {
            System.out.println(queue.peek());
            list3.add(queue.poll());
        }

    }

Is there another way of solving this with better time complexity or space complexity?

There is no need to use the extra priority queue.

This problem can be solved using 2 methods:

Method 1:

First concatenate the 2 lists and then sort.

Considering, Size of list 1 = n and Size of list 2 = m

Time complexity: O((n+m) log(n+m))

Auxiliary Space complexity: O(n+m)

Method 2:

First sort both lists and then merge.

Time complexity: O( nlog(n) + mlog(m) + (n+m))

Auxiliary Space complexity: O(n+m)

Conclusion: It is obvious from above time complexities that method 2 is better than method 1, and the space complexity for both methods remain the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM