java swap index from the end


  • 0

    http://www.geeksforgeeks.org/shuffle-a-given-array/

    class Solution {
        int[] nums;
        Random random;
        public Solution(int[] nums) {
            this.nums = nums;
            random = new Random();
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
             return nums;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            int[] shuffleNums = Arrays.copyOf(nums, nums.length);
            for (int i = shuffleNums.length - 1; i > 0; i--) {
                int j = random.nextInt(i + 1);
                int temp = shuffleNums[i];
                shuffleNums[i] = shuffleNums[j];
                shuffleNums[j] = temp;
            }
            return shuffleNums;
        }
    }
    

Log in to reply
 

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