LeetCode (3) - Shuffle an Array (파이썬, python)
❓ 문제
Given an integer array nums
, design an algorithm to randomly shuffle the array.
Implement the Solution
class:
Solution(int[] nums)
Initializes the object with the integer array nums.int[] reset()
Resets the array to its original configuration and returns it.int[] shuffle()
Returns a random shuffling of the array.
Example 1:
Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle(); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must be equally likely to be returned. Example: return [3, 1, 2]
solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]
Constraints:
1 <= nums.length <= 200
-10^6 <= nums[i] <= 10^6
- All the elements of
nums
are unique. - At most
5 * 10^4
calls will be made toreset
andshuffle
.
Given Code
class Solution:
def __init__(self, nums: List[int]):
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
접근법
init과 reset, shuffle을 적절히 이용하면 됩니다.
import random
class Solution:
def __init__(self, nums: List[int]):
self.data = nums
def reset(self) -> List[int]:
"""
Resets the array to its original configuration and return it.
"""
return self.data
def shuffle(self) -> List[int]:
"""
Returns a random shuffling of the array.
"""
output = []
datacopy = self.data.copy()
for _ in range(len(self.data)):
index = random.randint(0, len(datacopy) - 1)
output.append(datacopy[index])
del datacopy[index]
return output
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
init의 인자인 배열 nums를 self.data로 받아줍니다.
reset의 경우 오리지날 nums인 self.data를 반환하게 했습니다.
shuffle의 경우 random.randint를 사용했습니다. self.data를 복사한 datacopy에서 랜덤하게 하나씩 빼서 output이라는 배열로 지정한 뒤 output을 반환하게 했습니다. random.randint로 무작위의 datacopy의 index를 뽑아냈습니다.