[LeetCode]384. Shuffle an Array

    xiaoxiao2021-03-25  72

    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; } }

    转载请注明原文地址: https://ju.6miu.com/read-40861.html

    最新回复(0)