美文网首页
384. Shuffle an Array

384. Shuffle an Array

作者: Jeanz | 来源:发表于2017-08-31 07:52 被阅读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();

一刷
题解:类似于蓄水池算法
如果是第i个数字,有1/i的几率被留下。保证每个数字出现在每个位置的几率相同。

class Solution {
    private int[] nums;
    private Random random;
    
    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return nums;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        if(nums == null) return null;
        int[] a = nums.clone();
        for(int j = 1; j < a.length; j++) {
            int i = random.nextInt(j + 1);
            swap(a, i, j);
        }
        return a;
    }
    
    
    private void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int[] param_1 = obj.reset();
 * 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/sbvfjxtx.html