当前位置:网站首页>LeetCode-384. Scramble array

LeetCode-384. Scramble array

2022-06-11 16:59:00 Border wanderer

Give you an array of integers nums , Design algorithms to scramble an array without repeating elements .

Realization Solution class:

Solution(int[] nums) Using integer arrays nums Initialize object
int[] reset() Reset the array to its initial state and return
int[] shuffle() Returns the result of randomly scrambling the array
 

Example :

Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

explain
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // Scramble the array [1,2,3] And return the result . whatever [1,2,3] The probability of return should be the same . for example , return [3, 1, 2]
solution.reset();      // Reset the array to its initial state [1, 2, 3] . return [1, 2, 3]
solution.shuffle();    // Random return array [1, 2, 3] The result of the disruption . for example , return [1, 3, 2]
 

Tips :

1 <= nums.length <= 200
-106 <= nums[i] <= 106
nums All the elements in are Unique
You can call at most 5 * 104 Time reset and shuffle

#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;

class Solution {
public:
    Solution(vector<int>& nums) {
        source = nums;
        nochange = nums;
    }

    vector<int> reset() {
        return nochange;
    }

    vector<int> shuffle() {
        vector<int> result;
        vector<int>::iterator it = source.begin();
        while (!source.empty()) {
            int index = (rand() % (source.size()));
            result.push_back(source[index]);
            auto erase = source.begin() + index;
            source.erase(erase);
        }
        source = nochange;
        return result;
    }

private:
    vector<int> nochange;
    vector<int> source;
};

原网站

版权声明
本文为[Border wanderer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111653246571.html