[Leetcode]384. Shuffle an Array

本篇博客介绍了LeetCode上的第384题,即如何对一个不包含重复元素的数组进行随机洗牌。文章阐述了算法思路,即遍历数组并在指定范围内生成随机数进行交换,并提醒注意避免在`shuffle()`函数内部频繁创建新的数组空间,而应在类中声明一个成员变量来保存结果。
摘要由CSDN通过智能技术生成

题目[leetcode链接]
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();

思路:
随机洗牌问题

从头开始遍历,每次在[0,len)之间产生一个随机数,交换遍历到的位置与随机数位置上的数。

具体代码实现:

public class Solution {
    int[] nums;
    int[] result;

    public Solution(int[] nums) {
        int len = nums.length;
        this.nums = new int[len];
        result = new int[len];
        for (int i = 0; i < len; i++) {
            this.nums[i] = nums[i];
            result[i] = nums[i];
        }
    }

    /*  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 nums_len = nums.length;

        Random random = new Random();
        for (int i = 0; i < nums_len; i++) {
            int r = random.nextInt(nums_len);

            int temp = result[i];
            result[i] = result[r];
            result[r] = temp;

        }
        return result;
    }
}

需要注意的问题:

返回值result的创建不能在shuffle()函数中创建,这样每次shuffle都会新创建空间,浪费很多空间,应该如代码中写的 在类中创建一个成员变量,每次用都用这个就可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值