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

思路: 这里对无重复数的array进行等概率洗牌,洗牌算法用的是Fisher-Yates shuffle(Knuth shuffle).
reset的实现就是在构造器中把array拷贝一份就可以了。
shuffle的思路就是:选定一个idx, 在idx -> length(array) 范围内产生一个随机数r, 然后对应的array[r]的元素与array[idx]的元素进行交换。

import java.lang.*;

public class Solution {
    public int[] origin;
    public int[] nums;
    public Random rand;


    public Solution(int[] nums) {
        this.origin = new int[nums.length];
        System.arraycopy(nums, 0, origin, 0, nums.length);
        this.nums = nums;
        rand = new Random();
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return origin;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        for (int indexToPick = 0; indexToPick < nums.length; indexToPick++) {
            int valueAtIndex = getRandom(indexToPick, nums.length - 1);
            swap(nums, indexToPick, valueAtIndex);
        }
        return nums;
    }

    public int getRandom(int floor, int ceiling) {
        return rand.nextInt(ceiling - floor + 1) + floor;
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s