1
// Swap Tail Element Solution2
// 1. Get a random number between [0, size-1]4
// 3. Get the index in map by the random map5
// 4. Update the flipped element with the tail element.6
// Time complexity: O(1) to init, flip, and reset7
// Space complexity: O(K), where K is the times of flip calls.9
private final int M, N, CAPACITY;11
private Random random;12
private Map<Integer, Integer> map;14
public Solution(int m, int n) {19
random = new Random();20
map = new HashMap<>();24
if (size <= 0) return new int[] {-1, -1}; // or throw exception.25
Integer rand = random.nextInt(size);27
int idx = map.getOrDefault(rand, rand);28
Integer tail = map.getOrDefault(size, size);30
return new int[] {idx / N, idx % N};40
* Your Solution object will be instantiated and called as such: Solution obj = new Solution(m, n);41
* int[] param_1 = obj.flip(); obj.reset();