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();
在编写代码时,我涉及到要把基本int类型的数组转换成list和把list转换成int[],但是在调用Arrays.asList()和List.toArray()方法时遇到了问题。值得注意的是这两个方法都是针对引用类型使用的,对于基本类型int,long,boolean等是存在问题的,具体的解决方法可以用引入额外的包函数Apache Commons Lang来解决或者使用Integer封装类型等方法。关于两者的区别可以参考一下文章:把Java数组转换为List时的注意事项;Convert list to array in Java - StackOverFlow;Array.asList:数组转list时你一定要知道的“陷阱”
代码如下:
class Solution {
int[] nums;
public Solution(int[] nums) {
this.nums = new int[nums.length];
for(int i = 0; i < nums.length; i++)
this.nums[i] = nums[i];
}
/** 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() {
List<Integer> list = new ArrayList<>();
for(int i : nums)
list.add(i);
int n = nums.length;
Random random = new Random();
int index;
List<Integer> resList = new ArrayList<>();
for(int i = n-1; i >=0; i--){
index = random.nextInt(i+1);
resList.add(list.remove(index));
}
int i = 0;
int[] res = new int[n];
for(Integer num : resList)
res[i++] = num;
return res;
}
}
/**
* 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();
*/