白菜刷LeetCode记-384. Shuffle an Array
今天早上是一道中等难度的题目,考的是洗牌算法。
个人对洗牌算法还是比较不熟悉的,因此是看答案的。参考链接为: https://www.jianshu.com/p/44100741cef5
基本思路为:
1) 将第一个元素与 n 个元素中的任意一个交换;
2) 将第二个与 n - 1 个元素进行交换;
3) 重复上述步骤,直到剩下1个元素。
代码如下:
1 var original; 2 var copy; 3 var num; 4 /** 5 * @param {number[]} nums 6 */ 7 var Solution = function(nums) { 8 original = nums; 9 copy = original.concat(); 10 num = original.length; 11 }; 12 13 14 /** 15 * Resets the array to its original configuration and return it. 16 * @return {number[]} 17 */ 18 Solution.prototype.reset = function() { 19 return original; 20 }; 21 22 /** 23 * Returns a random shuffling of the array. 24 * @return {number[]} 25 */ 26 Solution.prototype.shuffle = function() { 27 let n = num; 28 while(n>1){ 29 n--; 30 let k = Math.floor(Math.random()*(n+1)); 31 let value = copy[k]; 32 copy[k] = copy[n]; 33 copy[n] = value; 34 } 35 36 return copy; 37 }; 38 39 /** 40 * Your Solution object will be instantiated and called as such: 41 * var obj = Object.create(Solution).createNew(nums) 42 * var param_1 = obj.reset() 43 * var param_2 = obj.shuffle() 44 */
END