Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
------------------------------------------------------------
What a pity for the bug:
import random
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
return list(self.nums)
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
res = list(self.nums)
l = len(res)
for i in range(l-1):
j = random.randint(i,l-1) #bug1: random.randint(i+1,l-1)
res[i],res[j] = res[j],res[i]
return res
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

本文介绍了一种用于洗牌算法的实现方法,通过随机选择数组元素进行交换,达到数组元素随机排列的效果。文章提供了详细的代码示例,包括初始化数组、重置数组到原始状态以及返回随机排列的数组等功能。
463

被折叠的 条评论
为什么被折叠?



