24.小R的随机播放顺序<字节青训营-中等题>

1.题目

问题描述

小R有一个特殊的随机播放规则。他首先播放歌单中的第一首歌,播放后将其从歌单中移除。如果歌单中还有歌曲,则会将当前第一首歌移到最后一首。这个过程会一直重复,直到歌单中没有任何歌曲。

例如,给定歌单 [5, 3, 2, 1, 4],真实的播放顺序是 [5, 2, 4, 1, 3]

保证歌曲中的id两两不同。


测试样例

样例1:

输入:n = 5 ,a = [5, 3, 2, 1, 4]

输出:[5, 2, 4, 1, 3]

样例2:

输入:n = 4 ,a = [4, 1, 3, 2]

输出:[4, 3, 1, 2]

样例3:

输入:n = 6 ,a = [1, 2, 3, 4, 5, 6]

输出:[1, 3, 5, 2, 6, 4]

2.思路

用队列存放原始歌单,模拟题目中的播放规则

3.代码

复制代码
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

std::vector<int> solution(int n, std::vector<int> a) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    queue<int> original_playlist; // 原始歌单
    vector<int> final_playlist; // 最终播放顺序
    // 将原始歌单放入队列中
    for (int i = 0; i < a.size(); i++) {
        original_playlist.push(a[i]);

    }
    while (original_playlist.size() != 0) {
        // 播放歌单中的第一首歌
        int cur = original_playlist.front();
        final_playlist.push_back(cur); 
        // 播放后将其从歌单中移除
        original_playlist.pop();
        // 当前第一首歌移到最后一首
        cur = original_playlist.front();
        original_playlist.pop();
        original_playlist.push(cur);
    }
    return final_playlist;
}

int main() {
    std::vector<int> result1 = {5, 2, 4, 1, 3};
    std::vector<int> result2 = {4, 3, 1, 2};
    std::vector<int> result3 = {1, 3, 5, 2, 6, 4};

    std::cout << (solution(5, {5, 3, 2, 1, 4}) == result1) << std::endl;
    std::cout << (solution(4, {4, 1, 3, 2}) == result2) << std::endl;
    std::cout << (solution(6, {1, 2, 3, 4, 5, 6}) == result3) << std::endl;
}
相关推荐
88号技师21 分钟前
2026年4月一区SCI-狒狒优化算法Baboon optimization algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
凯瑟琳.奥古斯特38 分钟前
BFS解力扣1654最短跳跃次数
数据结构·算法·广度优先
sg_knight39 分钟前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
m0_6294947339 分钟前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
炸膛坦客44 分钟前
嵌入式 - 数据结构与算法:(1-10)排序算法 - 冒泡排序(Bubble Sort)
算法·排序算法
Hello eveybody1 小时前
介绍一下动态树LCT(Python)
开发语言·python·算法
不穿铠甲的穿山甲1 小时前
MMR最大边际相关性
算法
handler011 小时前
速通蓝桥杯省一:二分算法
c语言·开发语言·c++·笔记·算法·职场和发展·蓝桥杯
炽烈小老头1 小时前
【 每天学习一点算法 2026/05/08】最小覆盖子串
学习·算法
汉克老师1 小时前
GESP5级C++考试语法知识(十六、分治算法(三))
c++·算法·分治算法·汉诺塔·逆序对·gesp5级·gesp五级