From 96e5528fa22378180abe0c41ca7df4a567a31605 Mon Sep 17 00:00:00 2001 From: GauravRatnawat Date: Mon, 1 Nov 2021 13:41:23 +0530 Subject: [PATCH] Solution for 154 Merge K-Sorted Arrays --- src/com/company/Heaps/MergeKSorted.java | 58 +++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/com/company/Heaps/MergeKSorted.java diff --git a/src/com/company/Heaps/MergeKSorted.java b/src/com/company/Heaps/MergeKSorted.java new file mode 100644 index 0000000..1ca45fa --- /dev/null +++ b/src/com/company/Heaps/MergeKSorted.java @@ -0,0 +1,58 @@ +package Heap; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.PriorityQueue; + +public class KWayMerge { + public static void main(String[] args) { + List> lists = Arrays.asList(Arrays.asList(10, 15, 20, 30), Arrays.asList(2, 5, 8, 14, 24), + Arrays.asList(0, 11, 60, 90)); + List result = merge(lists); + System.out.println(result); + } + + private static List merge(List> lists) { + //logic + List outPut = new ArrayList<>(); + // triplet of (value, array_index,value_index) + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(o -> o.value)); + + for (int i = 0; i < lists.size(); i++) { + Element e = new Element(lists.get(i).get(0), 0, i); + pq.offer(e); + } + + while (!pq.isEmpty()) { + Element peek = pq.peek(); + pq.remove(); + + int elem = peek.value; + int arrayIndex = peek.row; + int elemIndex = peek.idx; + + outPut.add(elem); + + if (elemIndex + 1 < lists.get(arrayIndex).size()) { + pq.offer(new Element(lists.get(arrayIndex).get(elemIndex + 1), elemIndex + 1, arrayIndex)); + } + } + + return outPut; + } + +} + +class Element { + int value; + int idx; + int row; + + public Element(int value, int idx, int row) { + this.value = value; + this.idx = idx; + this.row = row; + } +} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy