美文网首页
384. Shuffle an Array

384. Shuffle an Array

作者: a_void | 来源:发表于2016-09-28 23:06 被阅读0次

Shuffle a set of numbers without duplicates.
Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

Solution:

class Solution {
public:
    vector<int> v;
    int size;
    Solution(vector<int> nums) {
        v = nums;
        size = nums.size();
        srand(time(0));
    }
    
    /** 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> t(v);
        for(int i=0;i<size - 1;i++){
            int r = randomBetween(i, size-1);
            swap(t[i], t[r]);
        }
        return t;
    }
    
    inline void swap(int &a, int &b){
        int t = a;
        a = b;
        b = t;
    }
    
    int randomBetween(int a, int b){
        if(a == b) return a;
        if(a > b) return randomBetween(b, a);
        return rand() % (b-a+1) + a;
    }
};

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

相关文章

  • 384. Shuffle an Array

    题目分析 原题链接,登录 LeetCode 后可用这道题目要求我们完善 shuffle 方法,将一个数组进行乱序操...

  • 384. Shuffle an Array

    Shuffle a set of numbers without duplicates. Example: 一刷题...

  • 384. Shuffle an Array

    Shuffle a set of numbers without duplicates.Example:// In...

  • 384. Shuffle an Array

    Shuffle a set of numbers without duplicates.Example: Solu...

  • 384. Shuffle an Array

    Shuffle a set of numbers without duplicates. Example: // ...

  • 384. Shuffle an Array

    暴力解法 将每个数都放入一个帽子里,每次从帽子中随机摸出一个数,直到为空。 时间复杂度:O(n^2),乘方时间复杂...

  • 【Leetcode】384. Shuffle an Array

    自己想复杂了,用一个dictionary存储了所有的permutation,然后shuffle的时候直接产生一个随...

  • (随机)384. 打乱数组

    384. 打乱数组[https://leetcode-cn.com/problems/shuffle-an-arr...

  • Shuffle an Array

    打乱一个没有重复元素的数组。 示例: // 以数字集合 1, 2 和 3 初始化数组。int[] nums = {...

  • Shuffle an Array

    题目来源要求将一个数组随机打乱。不会…看了下答案,需要用到随机洗牌算法,介绍可以看这里。只需要从后往前遍历,每次随...

网友评论

      本文标题:384. Shuffle an Array

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