资讯专栏INFORMATION COLUMN

[LeetCode] 384. Shuffle an Array

Joyven / 1254人阅读

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 Note

Random random = new Random();

manipulate on a copy of given array, so that reset() would work;

int j = random.nextInt(i+1); then swap A[i] and A[j].

class Solution {

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

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

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

相关文章

  • 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
  • [LeetCode] 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 ...

    Baaaan 评论0 收藏0
  • GTAV智能驾驶源码详解(二)——Train the AlexNet

    摘要:智能驾驶源码详解二模型简介本使用进行图像分类前进左转右转。其性能超群,在年图像识别比赛上展露头角,是当时的冠军,由团队开发,领头人物为教父。 GTAV智能驾驶源码详解(二)——Train the AlexNet 模型简介: 本AI(ScooterV2)使用AlexNet进行图像分类(前进、左转、右转)。Alexnet是一个经典的卷积神经网络,有5个卷积层,其后为3个全连接层,最后的输出...

    jayzou 评论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

发表评论

0条评论

Joyven

|高级讲师

TA的文章

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