2017校招-网易有道 构造队列

本文介绍了一种利用Java中的Deque(双端队列)解决特定数字序列转换问题的方法。通过逆序添加数字并循环调整队列元素位置,最终得到转换后的序列。此算法与LeetCode上一道题目类似,但提供了更简洁的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:https://www.nowcoder.com/practice/657d09e2b3704574814089ba8566d98d?tpId=85&tqId=29849&tPage=1&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking

这个题目和LeetCode上的某道题比较类似,不过记得LeetCode是根据输入的1…n求转换之后的结果,当时涉及到偶数位的取模判断

这道题直接使用Java中的Deque(Double ended queue) API就很简单,构造一个双向队列
(1)每次从1…n中逆序取出有一个数字,放在队列头部
(2)然后取出队列尾部的元素,放回队列头部

package Interview2017.No1;

import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int cnt = in.nextInt();
        int[] input = new int[cnt];
        for(int i=0; i < cnt; i++){ //获取输入
            input[i] = in.nextInt();
        }
        for(int i=0; i < cnt; i++){ //处理逻辑
            int n = input[i];
            //Queue<Integer> queue = new LinkedList<Integer>();
            Deque<Integer> queue = new ArrayDeque<Integer>();
            while(n > 0){
                queue.addFirst(n);
                int tail = queue.removeLast();
                queue.addFirst(tail);
                n--;
            }
            int size = queue.size();
            for(int j=0; j < size; j++){
                if(j != size-1)
                    System.out.print(queue.getFirst() + " ");
                else
                    System.out.println(queue.getFirst());
                queue.removeFirst();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值