java - 在 Java 中使用队列对元素进行排序
问题描述
我正在尝试使用另一个队列对队列中存在的元素(整数)进行排序。队列没有负数或重复值队列必须按升序排序。(头->尾)示例输入:4 [7 3 9 5]
输出:[3 5 7 9]
import java.util.*;
public class Source {
public static void main(String args[]) {
Queue<Integer> queue = new LinkedList<Integer>();
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while (n-- > 0)
queue.add(s.nextInt());
sort(queue);
}
// Method to sort the queue
static void sort(Queue<Integer> queue) {
Queue<Integer> queue2 = new LinkedList<Integer>();
queue2.add(queue.remove());
while(queue.size()!=0){
int temp = queue.remove();
queue2.add(temp);
while(temp<queue2.peek()){
queue2.add(queue2.remove());
}
}
System.out.println(queue2);
}
}
解决方案
由于队列中没有负数,我想按如下方式操作:
1. 在第一个队列中插入一个负数(“虚拟”技术)。
2.在第一个队列中搜索最小的数字,直到你碰到假人。
3. 移除假人。
4. 在队列中搜索您在步骤 2 中找到的最小值,将其移除并将其插入到第二个队列中。
5. 执行这 4 个步骤,直到第一个队列为空。
Java代码:
static void sort(Queue<Integer> q1) {
Queue<Integer> q2 = new Queue<Integer>();
int min=Integer.MAX_VALUE;
while (!q1.isEmpty())
{
q1.insert(-1);
while(q1.head() != -1)
{
if (q1.head() < min)
{
min=q1.head();
}
q1.insert(q1.remove());
}
q1.remove(); //removing the -1
while (q1.head() != min)
{
q1.insert(q1.remove());
}
min = Integer.MAX_VALUE;
q2.insert(q1.remove()); //inserting the minimum to the second queue.
}
System.out.println(q2);
}
推荐阅读
- javascript - 如何将按钮从屏幕中间移动到屏幕底部
- wordpress - 仅在我的自定义 wordpress 插件中添加条件以删除挂钩
- android - ListView Displays all of the data from Firebase issue
- reactjs - 如何为 Algolia React 即时搜索键入自定义小部件?
- javascript - 动画平滑宽度变化
- typescript - 访问 Typescript 对象中的动态二级属性
- docker - Login failed for user 'sa'
- azure-functions - Azure functions signalR to create chat app?
- python - 将数据上传到 S3 存储桶而不将其保存到磁盘
- laravel - get page number in object of laravel