如何解决如何在O1空间中打印PriorityQueue的降序
我正在解决堆上的问题,我希望使用PriorityQueue以降序排列输出问题。
输入:
1
5 2
12 5 787 1 23
输出:
23 787
想要的输出:
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) {
// take array and kth element iput
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> minHeap = new PriorityQueue<Integer>();
// delete the minimum element in the element and just keep
// k greater element in the minHeap
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();
}
}
// print remaining element
//HERE IS THE PROBLEM I WANT IT IN " DECREASING ORDER "
// it gives me Increasing order
while(minHeap.size() > 0) {
System.out.print(minHeap.peek()+" ");
minHeap.poll();
}
System.out.println();
}// end of while
}// end of main
}// end of class
输入:
1
5 2
12 5 787 1 23
输出:
23 787
解决方法
您可以使用select cast(actual_qty as decimal(18,2)) as qty
from `Bin`
where warehouse = `Warehouse`.name
order by cast(actual_qty as decimal(18,2)) desc
打印结果:
Stream
,
只需在下面替换您的代码即可。
在声明优先级队列的同时,您可以为比较器提供相反的顺序。
PriorityQueue newHeap =新的PriorityQueue(minHeap.size(),Comparator.reverseOrder());
在这里,我创建了一个新堆,它将以反向顺序存储所有现有元素,然后按原样执行所有现有操作。
正在给出预期的答案。
1
5 2
12 5 787 1 23
O/P
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<Integer>();
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();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。