xinyu04

导航

LeetCode 384 Shuffle an Array

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

Implement the Solution class:

  • Solution(int[] nums) Initializes the object with the integer array nums.
  • int[] reset() Resets the array to its original configuration and returns it.
  • int[] shuffle() Returns a random shuffling of the array.

Solution

点击查看代码
class Solution {
private:
    vector<int> tmp;
    vector<int> ans;
    
public:
    Solution(vector<int>& nums) {
        srand(time(NULL));
        tmp = nums;
        ans = nums;
    }
    
    vector<int> reset() {
        return tmp;
    }
    
    vector<int> shuffle() {
        for(int i=0;i<ans.size();i++){
            int j = rand()%ans.size();
            swap(ans[i], ans[j]);
        }
        return ans;
    }
};

/**
 * 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();
 */

posted on 2022-08-16 21:27  Blackzxy  阅读(13)  评论(0编辑  收藏  举报