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;
}
相关推荐
满分观察网友z7 分钟前
从混乱到有序:我用“逐层扫描”法优雅搞定公司组织架构图(515. 在每个树行中找最大值)
后端·算法
满分观察网友z14 分钟前
一行代码的惊人魔力:从小白到大神,我用递归思想解决了TB级数据难题(3304. 找出第 K 个字符 I)
后端·算法
字节卷动22 分钟前
【牛客刷题】活动安排
java·算法·牛客
yi.Ist1 小时前
数据结构 —— 键值对 map
数据结构·算法
s153351 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔1 小时前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七1 小时前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
DoraBigHead2 小时前
小哆啦解题记——异位词界的社交网络
算法
木头左3 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
lifallen7 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree