384. Shuffle an Array (Medium)

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

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

Hints

Solutions

  • Java

http://www.cnblogs.com/grandyang/p/5783392.html

class Solution {

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

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        for (int i = 0; i < nums.length; i++) numsCopy[i] = nums[i];

        return nums;
    }

    private void swap(int[] nums, int x, int y) {
        int tmp = nums[x];     
        nums[x] = nums[y];
        nums[y] = tmp;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        for (int i = numsCopy.length-1; i>=0; i--) {
            int randIdx = (int)(Math.random() * (i + 1));
            swap(numsCopy, randIdx, i);
        }

        return numsCopy;
    }
}

/**
 * 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();
 */
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-04 00:16:07

results matching ""

    No results matching ""