资讯专栏INFORMATION COLUMN

[LeetCode] Shuffle an Array

Baaaan / 1459人阅读

Problem

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 {
    private int[] nums;
    public Solution(int[] nums) {
        this.nums = nums;
    }
    
    /** 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() {
        int[] rand = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            //we shuffle the array by getting random index j 
            //which is less than current index i, 
            //and swap their values
            int j = (int) (Math.random()* (i+1)); //(i+1) is the range
            rand[i] = rand[j];
            rand[j] = nums[i];
        }
        return rand;
    }
}

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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69262.html

相关文章

  • [LeetCode] 384. Shuffle an Array

    Problem 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...

    Joyven 评论0 收藏0
  • leetcode384. Shuffle an Array

    摘要:题目要求实现和方法,分别能够完成数组的随机打乱和还原。随机打乱即该数组中元素的所有排列组合结果都能够以等比例的概率输出。下面解释一下证明,即为何每个该结果是等概率的排列组合结果。 题目要求 Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. int[...

    cooxer 评论0 收藏0
  • 也谈前端面试常见问题之『数组乱序』

    摘要:看完部分的源码,首先迫不及待想跟大家分享的正是本文主题数组乱序。这是一道经典的前端面试题,给你一个数组,将其打乱,返回新的数组,即为数组乱序,也称为洗牌问题。关于数组乱序,正确的解法应该是,复杂度。 前言 终于可以开始 Collection Functions 部分了。 可能有的童鞋是第一次看楼主的系列文章,这里再做下简单的介绍。楼主在阅读 underscore.js 源码的时候,学到...

    tracy 评论0 收藏0
  • JDK Collections.shuffle(List<?> list, Random

    摘要:的源码如下一首先是判断要打乱的的属性的和是否实现接口如果的小于或者实现了接口,则直接交换内元素的位置。以上内容如有不正确的地方,欢迎支持。 jdk的源码如下 public static void shuffle(List list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRE...

    Aomine 评论0 收藏0
  • JavaScript30秒, 从入门到放弃之Array(五)

    摘要:原文地址秒,从入门到放弃之五博客地址秒,从入门到放弃之五水平有限,欢迎批评指正从给定的数组中随机选出指定个数的数组元素。否则判断数组元素是否大于或者等于指定元素,寻找过程与前边类似。 原文地址:JavaScript30秒, 从入门到放弃之Array(五)博客地址:JavaScript30秒, 从入门到放弃之Array(五) 水平有限,欢迎批评指正 sampleSize Gets n...

    dunizb 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<