[LeetCode]384. Shuffle an Array

来源:互联网 发布:英文app翻译软件 编辑:程序博客网 时间:2024/06/07 05:55

https://leetcode.com/problems/shuffle-an-array/#/description

shuffle一个数组







从前往后遍历,随机取已经遍历过的位置里面一个数与当前遍历到的位置交换

public class Solution {        int[] nums;    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;        }     // 又学一个api~        int[] a = nums.clone();        for (int i = 1; i < nums.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;    }}


0 0