(LeetCode) 384. Shuffle an Array

384. Shuffle an Array

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Design
  • 난이도 : Medium

Problem

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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 in total will be made to reset and shuffle.

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(nums: IntArray) {

val array = nums

/** Resets the array to its original configuration and return it. */
fun reset(): IntArray {
return array
}

/** Returns a random shuffling of the array. */
fun shuffle(): IntArray {
return array.clone().toList().shuffled().toIntArray()
}

}

/**
* Your Solution object will be instantiated and called as such:
* var obj = Solution(nums)
* var param_1 = obj.reset()
* var param_2 = obj.shuffle()
*/

Point of Thinking

  • 클래스 디자인 문제이다.
  • 주어진 nums를 별도로 아카이브해두면 reset 메서드는 바로 처리할 수 있다.
  • intArray를 shuffle하면 간단하게 끝날거라고 생각했는데, Array의 shuffle은 Unit을 반환한다.
  • 셔플 이후 객체를 얻기 위해 List로 변환 후 shuffled를 호출한 뒤, 다시 intArray로 변환하면 Accepted.
  • 아래 kotlin reference를 참고하자.
1
2
3
4
5
6
7
8
9
@SinceKotlin("1.4")
public fun IntArray.shuffle(random: Random): Unit {
for (i in lastIndex downTo 1) {
val j = random.nextInt(i + 1)
val copy = this[i]
this[i] = this[j]
this[j] = copy
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Returns a new list with the elements of this list randomly shuffled.
*/
@SinceKotlin("1.2")
public actual fun <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }

@SinceKotlin("1.2")
public actual fun <T> MutableList<T>.shuffle(): Unit {
for (i in lastIndex downTo 1) {
val j = Random.nextInt(i + 1)
val copy = this[i]
this[i] = this[j]
this[j] = copy
}
}