Shuffle an Array随机与取样--力扣101算法题解笔记

9.5Shuffle an Array随机与取样

题目描述

给定一个数组,要求实现两个指令函数,第一个函数"shuffle"可以随机打乱这个数组,第二个函数"reset"可以恢复原来的顺序

输入输出样例

Input :nums = 1, 2, 3, actions: "shuffle", "shuffle", "reset"

Output:\[2,1,3, 3,2,1,1,2,3]

题解

采用景点的Fisher-Yates洗牌算法,原理是通过随机交换位置来实现随机打乱,有正向和反向两种写法,实现很简单。

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

class Solution {
    vector<int> origin;
public:
    Solution(vector<int> nums) :origin(std::move(nums)) {}

    vector<int> reset() {
        return origin;
    }

    vector<int> shuffle() {
        if (origin.empty())  return {};
        vector<int> shuffled(origin);
        int n = origin.size();
        //反向洗牌
        for (int i = n - 1; i >= 0; --i) {
            swap(shuffled[i], shuffled[rand() % (i + 1)]);
        }
        //正向洗牌(跟反向效果一样)
        //for (int i = 0; i < n; ++i) {
        //    int pos = rand() % (n - i);
        //    swap(shuffled[i], shuffled[i + pos]);
        //}
        return shuffled;
    }
};

void printVector(const vector<int>& vec) {
    cout << "[";
    for (int i = 0; i < vec.size(); ++i) {
        cout << vec[i];
        if (i != vec.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

int main() {
    // 1. 初始化原始数组(对应样例输入nums = [1,2,3])
    vector<int> nums = { 1, 2, 3 };

    // 2. 创建Solution对象(注意:Solution solution(); 是函数声明,不是对象创建!)
    Solution solution(nums);

    // 3. 设置随机数种子(否则每次运行shuffle结果都一样)
    srand((unsigned)time(NULL));

    // 4. 模拟样例操作:shuffle → shuffle → reset
    cout << "第一次shuffle结果:";
    printVector(solution.shuffle()); // 输出随机打乱的数组(如[2,1,3])

    cout << "第二次shuffle结果:";
    printVector(solution.shuffle()); // 输出另一个随机打乱的数组(如[3,2,1])

    cout << "reset结果:";
    printVector(solution.reset());   // 输出原始数组[1,2,3]

    return 0;
}
相关推荐
无限的鲜花4 小时前
反射(原创推荐)
java·开发语言
yongche_shi4 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he4 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
QiLinkOS4 小时前
第三视觉理解徐玉生与他的商业活动(30)
大数据·c++·人工智能·算法·开源协议
mit6.8244 小时前
阅读的核心,是再读
c++
疯狂打码的少年5 小时前
【操作系统】页面置换算法(OPT/FIFO/LRU)
算法
小O的算法实验室5 小时前
2026年CIE,优化客货协同运输:综合地铁系统的列车容量动态分配
算法
AI行业学习5 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
Coder_Shenshen6 小时前
西门子S7CommPlus协议鉴权算法原理与流程详解
网络·后端·算法
大圣编程6 小时前
Python中continue语句的用法是什么?
开发语言·前端·python