Skip to main content

随机化

番风Less than 1 minute

水塘抽样知识点题库 - 力扣(LeetCode)open in new window

从数组中随机取出 n(n=3)个随机不重复的下标

for i in range(n): 
	rd = random.randint(0, n - i - 1)  # Adjust upper bound again 
	return_list.append(a[rd]) 
	del a[rd]  # Remove the chosen element from the list
const returnList: number[] = []; 
for (let i = 0; i < n; i++) { 
	const randomIndex = Math.floor(Math.random() * (arr.length - i)); // Adjusted upper bound 
	returnList.push(arr[randomIndex]); // Remove the chosen element from the original array (simulates del) 
	arr.splice(randomIndex, 1);
 }

蓄水池算法