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;
}
相关推荐
无定义_4 分钟前
Bellman-Ford——贝尔曼福特算法
数据库·算法
HanhahnaH43 分钟前
各数据结构操作的时间复杂度汇总
数据结构·算法
Yzzz-F1 小时前
CF2023D
c++·算法·dp
小小帅呀1 小时前
学习 VLA 第6天:SWIN VIT算法原理以及复现
学习·算法
猎头南楼2 小时前
杭州算法工程师,偏大模型应用落地
算法
间歇性努力持续性发呆的野生快乐选手2 小时前
二分模板(整型,浮点型)
数据结构·c++·算法
evans在进步2 小时前
LeetCode 189 轮转数组:三次反转为什么能实现右旋?
数据结构·算法·leetcode
豆沙沙包?2 小时前
函数重载/类和对象(P14-P60)
前端·算法
lingchen19062 小时前
用MATLAB r2010b和r2016b求解微分方程组
开发语言·算法·matlab