[Java] Swap Tail Element Solution with Explanation
\n// Swap Tail Element Solution\n// 1. Get a random number between [0, size-1]\n// 2. size - 1\n// 3. Get the index in map by the random map\n// 4. Update the f
```\n// Swap Tail Element Solution\n// 1. Get a random number between [0, size-1]\n// 2. size - 1\n// 3. Get the index in map by the random map\n// 4. Update the flipped element with the tail element.\n// Time complexity: O(1) to init, flip, and reset\n// Space complexity: O(K), where K is the times of flip calls.\nclass Solution {\n    private final int M, N, CAPACITY;\n    private int size;\n    private Random random;\n    private Map<Integer, Integer> map;\n        \n    public Solution(int m, int n) {\n        M = m;\n        N = n;\n        CAPACITY = m * n;\n        size = CAPACITY;\n        random = new Random();\n        map = new HashMap<>();\n    }\n    \n    public int[] flip() {\n        if (size <= 0) return new int[]{-1, -1}; // or throw exception.\n        Integer rand = random.nextInt(size);\n        size--;\n        int idx = map.getOrDefault(rand, rand);\n        Integer tail = map.getOrDefault(size, size);\n        map.put(rand, tail);\n        return new int[]{idx / N, idx % N};\n    }\n    \n    public void reset() {\n        map = new HashMap();\n        size = CAPACITY;\n    }\n}\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(m, n);\n * int[] param_1 = obj.flip();\n * obj.reset();\n */\n```
['Java']