力扣练习之打乱数组

我爱海鲸 2022-10-03 23:31:18 初级算法

简介初级算法、设计问题

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn6gq1/

解法一:

class Solution {

    private int[] nums;
    private Random random;


    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    public int[] reset() {
        return this.nums;
    }
    
    public int[] shuffle() {
        int[] copyNums = this.nums.clone();
        for (int i = 1; i < nums.length; i++) {
            int ran = random.nextInt(i+1);
            swap(copyNums,i,ran);
        }
        return copyNums;
    }
    private void swap(int[] nums,int i, int j) {
        if (i != j) {
            nums[i] ^= nums[j];
            nums[j] ^= nums[i];
            nums[i] ^= nums[j];
        }
    }

  
}

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

思路:根据题目的意思就是,能够打乱一个数组,也能还原一个数据,先将原数组保存起来,在方法reset中,就可以直接返回该数组。至于打乱数组,我们不能直接打乱原本的数组数据,我们需要复制一个副本,在打乱数据,最后返回被打乱的副本数组即可,那么怎么随机的去打乱一个数组呢?定义一个随机值,根据随机值判断打乱的元素。最后返回被打乱后的副本数组即可。

你好:我的2025