打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。 int[] nums = {1,2,3}; Solution solution = new Solution(nums); // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。 solution.shuffle(); // 重设数组到它的初始状态[1,2,3]。 solution.reset(); // 随机返回数组[1,2,3]打乱后的结果。 solution.shuffle();思路一
参考Knuth洗牌算法https://yjk94.wordpress.com/2017/03/17/%E6%B4%97%E7%89%8C%E7%9A%84%E6%AD%A3%E7%A1%AE%E5%A7%BF%E5%8A%BF-knuth-shuffle%E7%AE%97%E6%B3%95/
参考的代码块
def shuffleSort(a): N = len(a) for i in range(N): j = random.randint(0, i) a[j], a[i] = a[i], a[j]测试法
public static void main(String[] args) { int[] nums = new int[]{1,2,3}; Solution obj = new Solution(nums); int a =0; int b =0; int c =0; int d =0; int e =0; int f =0; for(int i = 0 ; i < 50000 ; i ++ ){ int[] param_1 = obj.shuffle(); if(param_1[0]==1&¶m_1[1]==2&¶m_1[2]==3){ a++; } if(param_1[0]==1&¶m_1[1]==3&¶m_1[2]==2){ b++; } if(param_1[0]==2&¶m_1[1]==1&¶m_1[2]==3){ c++; } if(param_1[0]==2&¶m_1[1]==3&¶m_1[2]==1){ d++; } if(param_1[0]==3&¶m_1[1]==2&¶m_1[2]==1){ e++; } if(param_1[0]==3&¶m_1[1]==1&¶m_1[2]==2){ f++; } } System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(e); System.out.println(f); }答案
class Solution { private int[] nums; private int[] copyNums; public Solution(int[] nums) { this.nums = nums; this.copyNums = Arrays.copyOf(nums,nums.length); } /** Resets the array to its original configuration and return it. */ public int[] reset() { return copyNums; } /** Returns a random shuffling of the array. */ public int[] shuffle() { int length = nums.length; int temp= 0; for(int i = 0; i < length; i ++){ int j = (int)(Math.random()*(i+1)); temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } return nums; } }