LeetCode:Shuffle an Array(打乱数组)

题目

Shuffle a set of numbers without duplicates.

Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

思路

这道题感觉很不错,可以考察类的基本使用方法:构造、成员函数等的使用。

首先来看类的构造函数,使用初始化列表方法给成员变量赋值,简洁方便。

Solution(vector<int> nums) : m_nums(nums){

    }

两个成员函数,要实现返回原数组和乱序后数组的功能。其中,返回原数组实现十分简单,在乱序时不对成员变量数组进行操作,要原数组只需要返回成员变量数组即可。因此返回乱序数组时首先定义一个新数组并赋值,然后对其进行乱序。这里直接使用STL库的random_shuffle函数即可。

下面来看random_shuffle函数,需要两个参数(first,last),first指乱序起始元素的迭代器,last指乱序终止元素的迭代器,例如:对于一个数组vector nums的全部数据进行乱序,使用方法为random_shuffle(nums.begin(),nums.end());

代码

class Solution {
public:
    vector<int>  m_nums;

    Solution(vector<int> nums) : m_nums(nums){

    }

    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return m_nums;
    }

    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> temp(m_nums);
        random_shuffle(temp.begin(),temp.end());
        return temp;
    }
};
/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * vector param_1 = obj.reset();
 * vector param_2 = obj.shuffle();
 */

你可能感兴趣的:(刷题,刷题笔记)