Is the question implying that we must use the original array to shuffle?


  • 0
    B

    Originally, when shuffle() is called more than once, I used the previous shuffled result for new shuffling, however my code couldn't get passed OJ so I change to reset the array every time I call shuffle() and OJ accepted. I mean technically the shuffling is not affected by the input's permutation, and I wonder if the question is implying that?

    Below is my ac code, I commented where I've changed

    public class Solution {
        int[] ori;
        Random r;
        public Solution(int[] nums) {
            ori = nums;
            r = new Random();
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return ori;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            int arr[] = Arrays.copyOf(ori, ori.length); //originally I don't have this part and arr was an instance variable, but won't pass OJ
            int len = arr.length;
            int res[] = new int[len];
            for(int i = 0; i < len; i++) {
                int idx = r.nextInt(len - i);
                res[i] = arr[idx];
                //swap
                int tmp = arr[idx];
                arr[idx] = arr[len - 1 - i];
                arr[len - 1 - i] = tmp;
            }
            return res;
        }
    }
    

  • 0
    S

    Yes, it seems so. My code was passing only 6/10 test cases. The rest worked when I used the original array to shuffle.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.