原题
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();
解法1
在shuffle函数里, 深度复制nums至ans, 从ans末尾到开头遍历, 每次随机选择一个index, 然后交换数值, 最后返回ans. 原来的nums不变.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.data = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.data
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
ans = copy.deepcopy(self.data)
for i in range(len(ans)-1, -1, -1):
# choose an index randomly
j = random.randint(0, i)
# swap the value
ans[i], ans[j] = ans[j], ans[i]
return ans
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
解法2
使用random.shuffle()方法
代码
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.data = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.data
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
ans = copy.deepcopy(self.data)
random.shuffle(ans)
return ans