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

Solutions

  • golang
type Solution struct {
    Nums []int
    Origin []int
}


func Constructor(nums []int) Solution {
    var s Solution
    s.Nums = make([]int, len(nums))
    s.Origin = make([]int, len(nums))
    copy(s.Nums,nums)
    copy(s.Origin,nums)
    return s
}


/** Resets the array to its original configuration and return it. */
func (this *Solution) Reset() []int {
    return this.Origin
}


/** Returns a random shuffling of the array. */
func (this *Solution) Shuffle() []int {
    rand.Seed(time.Now().UnixNano()) 
    for i := range this.Nums {
        j := rand.Intn(i + 1)
        this.Nums[i], this.Nums[j] = this.Nums[j], this.Nums[i]
    }
    return this.Nums
}


/**
 * Your Solution object will be instantiated and called as such:
 * obj := Constructor(nums);
 * param_1 := obj.Reset();
 * param_2 := obj.Shuffle();
 */
  • scala
class Solution(_nums: Array[Int]) {

    /** Resets the array to its original configuration and return it. */
    def reset(): Array[Int] = {
        return _nums
    }

    /** Returns a random shuffling of the array. */
    def shuffle(): Array[Int] = {
        return scala.util.Random.shuffle(_nums.toList).toArray
    }

}

/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(nums)
 * var param_1 = obj.reset()
 * var param_2 = obj.shuffle()
 */

results matching ""

    No results matching ""