You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * @param {number[]} nums */varSolution=function(nums){this.nums=nums;};/** * Resets the array to its original configuration and return it. * @return {number[]} */Solution.prototype.reset=function(){returnthis.nums;};/** * Returns a random shuffling of the array. * @return {number[]} */Solution.prototype.shuffle=function(){letnum=this.nums.slice();for(leti=0;i<num.length;i++){letindex=Math.floor((i+1)*Math.random());[num[index],num[i]]=[num[i],num[index]]}returnnum;};
sort(() => Math.random() - 0.5)
sort() 会根据 compareFunction(a, b) 的返回值,来决定 a 和 b 的相对位置:
如果 compareFunction(a, b) 小于 0 ,那么 a 会被排列到 b 之前;
如果 compareFunction(a, b) 大于 0 ,那么 b 会被排列到 a 之前;
如果 compareFunction(a, b) 等于 0 , a 和 b 的相对位置不变(不稳定!)
/** * @param {number[]} nums */varSolution=function(nums){this.origin=nums};/** * Resets the array to its original configuration and return it. * @return {number[]} */Solution.prototype.reset=function(){returnthis.origin};/** * Returns a random shuffling of the array. * @return {number[]} */Solution.prototype.shuffle=function(){letcopyArr=[...this.origin];letlen=copyArr.length;for(leti=len-1;i>=0;i--){letindex=~~(Math.random()*(i+1));[copyArr[index],copyArr[i]]=[copyArr[i],copyArr[index]];}returncopyArr;};/** * Your Solution object will be instantiated and called as such: * var obj = new Solution(nums) * var param_1 = obj.reset() * var param_2 = obj.shuffle() */
function shuffle(arr) {
let len = arr.length;
let i, t;
while (len) {
// /随机索引值i是从0-arr.length中随机抽取的
i = Math.floor(Math.random() * (len--))
//把从数组中随机抽取到的值与当前遍历的值互换位置
t = arr[len]
arr[len] = arr[i];
arr[i] = t
}
return arr
}
Activity
[-]蚂蚁金服/字节跳动/Bigo/网易:洗牌算法[/-][+]蚂蚁金服&字节跳动&Bigo&网易leetcode384:打乱数组(洗牌算法)[/+][-]蚂蚁金服&字节跳动&Bigo&网易leetcode384:打乱数组(洗牌算法)[/-][+]leetcode384:打乱数组(洗牌算法)[/+]7777sea commentedon Jul 1, 2020
浅拷贝数组,利用random()方法重制数组角标
xyj626553989 commentedon Jul 1, 2020
Cxy56 commentedon Jul 1, 2020
sort(() => Math.random() - 0.5)
sort() 会根据 compareFunction(a, b) 的返回值,来决定 a 和 b 的相对位置:
如果 compareFunction(a, b) 小于 0 ,那么 a 会被排列到 b 之前;
如果 compareFunction(a, b) 大于 0 ,那么 b 会被排列到 a 之前;
如果 compareFunction(a, b) 等于 0 , a 和 b 的相对位置不变(不稳定!)
真正乱排序:
最后一位开始往前遍历。每次循环生成随机数:
math.random()*(i+1) , 向下取整,然后两个位置元素交换;
实现真正的乱序
syc666 commentedon Jul 1, 2020
sisterAn commentedon Jul 2, 2020
解答:Fisher-Yates 洗牌算法
复杂度分析:
reset功能,原始数组必须得保存一份AnranS commentedon Nov 20, 2020
XW666 commentedon Mar 1, 2022