[LeetCode 384] Shuffle an Array
2019-06-11 本文已影响0人
灰睛眼蓝
class Solution {
int[] originNums;
public Solution(int[] nums) {
originNums = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
originNums[i] = nums[i];
}
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return originNums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
int[] shuffleNums = new int[originNums.length];
for (int i = 0; i < originNums.length; i++) {
shuffleNums[i] = originNums[i];
}
for (int i = 0; i < shuffleNums.length; i++) {
Random rand = new Random ();
int randomIndex = rand.nextInt (shuffleNums.length - 1 - i + 1) + i;
int temp = shuffleNums[randomIndex];
shuffleNums[randomIndex] = shuffleNums[i];
shuffleNums[i] = temp;
}
return shuffleNums;
}
}
/**
* 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();
*/