zoukankan      html  css  js  c++  java
  • 【LeetCode-数学】打乱数组

    题目描述

    打乱一个没有重复元素的数组。
    示例:

    // 以数字集合 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();
    

    题目链接: https://leetcode-cn.com/problems/shuffle-an-array/

    思路

    重设到初始状态比较好做,只需要再使用一个数组 copy 保存原来的数组 nums,重设的时候将 nums 设为 copy 即可。

    打乱可以使用 Fisher-Yates 洗牌算法,也就是遍历 nums,假设当前的下标为 i,则生成一个 [i, nums.size()-1] 之间的随机数 idx,swap(nums[i], nums[idx]) 即可。代码如下:

    class Solution {
        vector<int> nums;
        vector<int> copy;
    public:
        Solution(vector<int>& nums) {
            this->nums = nums;
            this->copy = nums;
        }
        
        /** Resets the array to its original configuration and return it. */
        vector<int> reset() {
            nums = copy;
            return nums;
        }
        
        /** Returns a random shuffling of the array. */
        vector<int> shuffle() {
            for(int i=0; i<nums.size(); i++){
                int idx = rand()%nums.size();
                swap(nums[i], nums[idx]);
            }
            return nums;
        }
    };
    
    /**
     * 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();
     */
    
  • 相关阅读:
    【Learning】积性函数前缀和——洲阁筛(min_25写法)
    GDOI2018记录
    最近公共祖先(一道题目)
    Counting
    【BZOJ4872】【Shoi2017】分手是祝愿
    【BZOJ2654】tree
    数学竞赛
    A
    【bzoj 3131】[Sdoi2013]淘金
    【Never Stop】联赛集训记录
  • 原文地址:https://www.cnblogs.com/flix/p/13283040.html
Copyright © 2011-2022 走看看