一、问题描述:
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();
二、解决思路:
针对reset函数,多建立一个数组存放原始数组即可。
针对shuffle函数,取随机数。用list存放元素,在第i 次rand一个1-list.length 之间的整数放在nums的第i位,从list中删除该元素,继续循环。
三、代码:
public class Solution {
private int[] nums;
private int[] orinums;
public Solution(int[] nums) {
this.nums = nums;
this.orinums = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return orinums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int len = nums.length;
int[] re = new int[len];
List<Integer> id = new ArrayList<Integer>();
for (int i = 0; i < len; i++) {
id.add(i);
}
for (int i = 0; i < nums.length; i++) {
Random r = new Random();
int rr = r.nextInt(len);
re[i] = nums[id.get(rr)];
id.remove(rr);
len--;
}
return re;
}
}