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();
     */
  • 相关阅读:
    Mayan游戏 (codevs 1136)题解
    虫食算 (codevs 1064)题解
    靶形数独 (codevs 1174)题解
    黑白棋游戏 (codevs 2743)题解
    神经网络 (codevs 1088) 题解
    The Rotation Game (POJ 2286) 题解
    倒水问题 (codevs 1226) 题解
    银河英雄传说 (codevs 1540) 题解
    生日蛋糕 (codevs 1710) 题解
    第一章 1.11 高阶函数
  • 原文地址:https://www.cnblogs.com/mikemeng/p/9000039.html
Copyright © 2011-2022 走看看