美文网首页
Leetcode384. 打乱数组

Leetcode384. 打乱数组

作者: LonnieQ | 来源:发表于2019-11-16 18:27 被阅读0次

题目

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

示例:

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

C++代码

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
    vector<int> copy;
    vector<int> numbers;
    Solution(vector<int>& nums): numbers(nums), copy(nums) {
        
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return numbers;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        for (int i = 0; i < copy.size(); ++i) {
            swap(copy[i], copy[rand() % copy.size()]);
        }
        return copy;
    }
};
int main(int argc, const char * argv[]) {
    vector<int> nums {1, 2, 3, 4, 5}, result;
    Solution solution(nums);
    result = solution.shuffle();
    for (auto item: result) cout << item << " ";
    cout << endl;
    result = solution.shuffle();
    for (auto item: result) cout << item << " ";
    cout << endl;
    return 0;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-an-array

相关文章

网友评论

      本文标题:Leetcode384. 打乱数组

      本文链接:https://www.haomeiwen.com/subject/blayictx.html