如何在 O(1) 空间复杂度下按递减顺序打印优先队列。

huangapple go评论86阅读模式
英文:

How to Print decreasing order of the PriorityQueue in O(1) Space

问题

class GFG {
    public static void main(String args[])throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        while(t-- > 0) {
            // take array and kth element input
            String n_k[] = br.readLine().split(" ");
            // store array size in n && kth element to find in k
            int n = Integer.parseInt(n_k[0]);
            int k = Integer.parseInt(n_k[1]);
            // Array String input
            String s[] = br.readLine().split(" ");
            int d[] = new int[n];
            for(int i = 0; i < n; i++) {
                d[i] = Integer.parseInt(s[i]);
            }

            PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
            // insert elements into the maxHeap
            for(int i = 0; i < n; i++) {
                maxHeap.add(d[i]);
            }
            
            // pop the top k elements from the maxHeap
            for(int i = 0; i < k; i++) {
                System.out.print(maxHeap.poll() + " ");
            }
            System.out.println();
        } // end of while
    } // end of main
} // end of class
英文:

Am solving problems on Heaps and i want the output for a problem in decreasing order, using PriorityQueue.
<br>Input:
<br>1
<br>5 2
<br>12 5 787 1 23
<br>Output:
<br>23 787
<br> Wanted Output:
<br> 787 23

class GFG {
public static void main(String args[])throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t--&gt;0) {
// take array and kth element iput
String n_k[] = br.readLine().split(&quot; &quot;);
// store array size in n &amp;&amp; kth element to find in k
int n = Integer.parseInt(n_k[0]);
int k = Integer.parseInt(n_k[1]);
// Array String input
String s[] = br.readLine().split(&quot; &quot;);
int d[] = new int[n];
for(int i = 0 ; i &lt; n ; i++) {
d[i] = Integer.parseInt(s[i]);
}
PriorityQueue&lt;Integer&gt; minHeap = new PriorityQueue&lt;Integer&gt;();
// delete the minimum element in the element and just keep 
// k greater element in the minHeap
for(int i = 0 ; i &lt; n; i++) {
minHeap.add(d[i]);
// if size of heap increases pop tht last element 
if(minHeap.size()&gt;k) {
minHeap.poll();
}
}
// print remaining element
//HERE IS THE PROBLEM I WANT IT IN &quot; DECREASING ORDER &quot;
// it gives me Increasing order
while(minHeap.size() &gt; 0) {
System.out.print(minHeap.peek()+&quot; &quot;);
minHeap.poll();
}
System.out.println();
}// end of while
}// end of main
}// end of class

Input:
<br>1
<br>5 2
<br>12 5 787 1 23
<br>Output:
<br>23 787

答案1

得分: 1

你可以使用 Stream 来打印结果:

try (Scanner scan = new Scanner(System.in)) {
    int totalCases = scan.nextInt();

    while (totalCases-- > 0) {
        int n = scan.nextInt();
        int k = scan.nextInt();

        Queue<Integer> minHeap = new PriorityQueue<>(k);

        for (int i = 0; i < n; i++) {
            if (minHeap.size() == k)
                minHeap.remove();

            minHeap.add(scan.nextInt());
        }

        System.out.println(minHeap.stream()
                                  .sorted(Comparator.reverseOrder())
                                  .map(String::valueOf)
                                  .collect(Collectors.joining(" ")));
    }
}
英文:

You can use Stream to print the result:

try (Scanner scan = new Scanner(System.in)) {
int totalCases = scan.nextInt();
while (totalCases-- &gt; 0) {
int n = scan.nextInt();
int k = scan.nextInt();
Queue&lt;Integer&gt; minHeap = new PriorityQueue&lt;&gt;(k);
for (int i = 0; i &lt; n; i++) {
if (minHeap.size() == k)
minHeap.remove();
minHeap.add(scan.nextInt());
}
System.out.println(minHeap.stream()
.sorted(Comparator.reverseOrder())
.map(String::valueOf)
.collect(Collectors.joining(&quot; &quot;)));
}
}

答案2

得分: 0

只需将您的代码替换为以下内容

在声明优先级队列时您可以使用反向顺序提供比较器

PriorityQueue<Integer> newHeap = new PriorityQueue<>(minHeap.size(), Comparator.reverseOrder());

这里我创建了一个新的 newHeap它将以反向顺序存储所有现有元素然后执行所有现有操作

它会给出预期的答案

1
5 2
12 5 787 1 23

输出
787 23

这将对您有所帮助

class GFG {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        while (t-- > 0) {
            String n_k[] = br.readLine().split(" ");
            int n = Integer.parseInt(n_k[0]);
            int k = Integer.parseInt(n_k[1]);
            String s[] = br.readLine().split(" ");
            int d[] = new int[n];
            for (int i = 0; i < n; i++) {
                d[i] = Integer.parseInt(s[i]);
            }

            PriorityQueue<Integer> minHeap = new PriorityQueue<>();
            for (int i = 0; i < n; i++) {
                minHeap.add(d[i]);
                // if size of heap increases pop tht last element
                if (minHeap.size() > k) {
                    minHeap.poll();
                }
            }
            PriorityQueue<Integer> newHeap = new PriorityQueue<>(minHeap.size(), Comparator.reverseOrder());
            newHeap.addAll(minHeap);
            while (newHeap.size() > 0) {
                System.out.print(newHeap.peek() + " ");
                newHeap.poll();
            }
            System.out.println();
        }

    }
}
英文:

Simply replace your code with below.

While declaring priority queue , you can provide comparator with reverse order.

PriorityQueue<Integer> newHeap = new PriorityQueue(minHeap.size(),Comparator.reverseOrder());

Here i had created one newHeap which will store all existing elements in reverseOrder and then doing all existing operation as it is.

It's giving expected answer.

1
5 2
12 5 787 1 23
O/P
787 23 

This will help you.

  class GFG {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- &gt; 0) {
String n_k[] = br.readLine().split(&quot; &quot;);
int n = Integer.parseInt(n_k[0]);
int k = Integer.parseInt(n_k[1]);
String s[] = br.readLine().split(&quot; &quot;);
int d[] = new int[n];
for (int i = 0; i &lt; n; i++) {
d[i] = Integer.parseInt(s[i]);
}
PriorityQueue&lt;Integer&gt; minHeap = new PriorityQueue&lt;Integer&gt;();
for (int i = 0; i &lt; n; i++) {
minHeap.add(d[i]);
// if size of heap increases pop tht last element
if (minHeap.size() &gt; k) {
minHeap.poll();
}
}
PriorityQueue&lt;Integer&gt; newHeap = new PriorityQueue(minHeap.size(), Comparator.reverseOrder());
newHeap.addAll(minHeap);
while (newHeap.size() &gt; 0) {
System.out.print(newHeap.peek() + &quot; &quot;);
newHeap.poll();
}
System.out.println();
}
}
}

huangapple
  • 本文由 发表于 2020年8月17日 04:20:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63441593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定