The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.
classSolution { privateint[] shuffleArr; privateint[] originalArr; publicSolution(int[] nums) { originalArr = nums.clone(); shuffleArr = nums.clone(); } /** Resets the array to its original configuration and return it. */ publicint[] reset() { return originalArr; } /** Returns a random shuffling of the array. */ publicint[] shuffle() { finalintN= shuffleArr.length; int swap; for (inti=0; i < N; i++) { intr= (int) (Math.random() * (i + 1)); swap = shuffleArr[r]; shuffleArr[r] = shuffleArr[i]; shuffleArr[i] = swap; } return shuffleArr; } }
/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int[] param_1 = obj.reset(); * int[] param_2 = obj.shuffle(); */
Submission Detail
10 / 10 test cases passed.
Runtime: 76 ms, faster than 76.75% of Java online submissions for Shuffle an Array.
Memory Usage: 47.2 MB, less than 6.24% of Java online submissions for Shuffle an Array.
/** Resets the array to its original configuration and return it. */ publicint[] reset() { return originalArr; }
/** Returns a random shuffling of the array. */ publicint[] shuffle() { List<Integer> list = Arrays.asList(shuffleArr); Collections.shuffle(list); Integer[] a = newInteger[shuffleArr.length]; list.toArray(a); int[] r = newint[a.length]; for(int i=0;i<a.length;i++) r[i] = a[i]; return r; } }
/** Initialize your data structure here. */ publicMyHashMap() { arr = newint[N]; Arrays.fill(arr, -1); }
/** value will always be non-negative. */ publicvoidput(int key, int value) { arr[key]=value; }
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ publicintget(int key) { return arr[key]; }
/** Removes the mapping of the specified value key if this map contains a mapping for the key */ publicvoidremove(int key) { arr[key]=-1; } }