zoukankan      html  css  js  c++  java
  • 【简单算法】37.Shuffle an Array

    题目:

    打乱一个没有重复元素的数组。
    
    示例:
    
    // 以数字集合 1, 2 和 3 初始化数组。
    int[] nums = {1,2,3};
    Solution solution = new Solution(nums);
    
    // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
    solution.shuffle();
    
    // 重设数组到它的初始状态[1,2,3]。
    solution.reset();
    
    // 随机返回数组[1,2,3]打乱后的结果。
    solution.shuffle();

    解题思路:

    reset操作:

    记录下数组的原始位置,reset操作时,直接返回原数组的拷贝即可。

    shuffle:

    将数组中的每个数与数组中的随机位置进行交换即可。关键点在于如何找到随机交换的位置,并且保证概率相同。

    及第i个数可能与数组中任意一个数进行交换。

    int t = (i + rand()%res.size())%(res.size());

    代码:

    class Solution {
    public:
        Solution(vector<int> nums) {
            v.insert(v.begin(), nums.begin(), nums.end());
        }
        
        /** Resets the array to its original configuration and return it. */
        vector<int> reset() {
            return v;
        }
        
        /** Returns a random shuffling of the array. */
        vector<int> shuffle() {
            vector<int> res = v;
            for (int i = 0; i < res.size(); ++i) {
                int t = i + rand() % (res.size() - i);
                swap(res[i], res[t]);
            }
            
            return res;
        }
    private:
        vector<int> v;
    };
    
    /**
     * 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();
     */
  • 相关阅读:
    sw
    ++1
    test
    为了
    发送邮件
    新建121212
    29012
    pthread_create/join函数
    recv函数学习
    socketpair用法学习
  • 原文地址:https://www.cnblogs.com/mikemeng/p/9000039.html
Copyright © 2011-2022 走看看