第384题 shuffle an array

  • 题意描述

    • 给定一个数组,把这个数组当作参数传给solution的类,实现这个类的构造函数,reset()函数还原这个数组,shuffle函数是这数组随机洗牌
  • 思路一

    • 定义两个数组,一个保存原来的数组,用于reset函数;一个数组用于随机洗牌函数,随机的算法是遍历数组,生成一个随机数,交换随机数的位置的值和当前位置的值,遍历完成
  • 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    class Solution {
    public:
    Solution(vector<int> nums) {
    temp = nums;
    orig = nums;
    }
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
    return orig;
    }
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
    int size = temp.size();
    for(int i = 0; i < size; ++i) {
    int random = rand() % size;
    swap(i, random);
    }
    return temp;
    }
    void swap(int a, int b) {
    int tmp = temp[a];
    temp[a] = temp[b];
    temp[b] = tmp;
    }
    private:
    vector<int> temp;
    vector<int> orig;
    };
    /**
    * Your Solution object will be instantiated and called as such:
    * Solution obj = new Solution(nums);
    * vector<int> param_1 = obj.reset();
    * vector<int> param_2 = obj.shuffle();
    */
坚持原创技术分享,您的支持将鼓励我继续创作!

热评文章