leetcode384: shuffle an array 2. Analysis 3. Solution(s)

Link

Shuffle a set of numbers without duplicates.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
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();

2. Analysis

Using python permutations and combinations package(itertools) or random package(shuffle)

3. Solution(s)

Permutations:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import itertools
import random
class (object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.array = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.array
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
reslist = list(itertools.permutations(self.array, len(self.array)))
print reslist
return reslist[random.randint(0, len(reslist)-1)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

random shuffle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import random
class (object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.array_original = self.array = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
self.array = self.array_original
return self.array
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
random.shuffle(self.array)
return self.array
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()