美文网首页
[LeetCode 384] Shuffle an Array

[LeetCode 384] Shuffle an Array

作者: 灰睛眼蓝 | 来源:发表于2019-06-11 15:22 被阅读0次
    class Solution {
        int[] originNums;
    
        public Solution(int[] nums) {
            originNums = new int[nums.length];
            for (int i = 0; i < nums.length; i++) {
                originNums[i] = nums[i];
            }
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return originNums;
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            int[] shuffleNums = new int[originNums.length];
            for (int i = 0; i < originNums.length; i++) {
                shuffleNums[i] = originNums[i];
            }
            
            for (int i = 0; i < shuffleNums.length; i++) {
                Random rand = new Random ();
                int randomIndex = rand.nextInt (shuffleNums.length - 1 - i + 1) + i;
                int temp = shuffleNums[randomIndex];
                shuffleNums[randomIndex] = shuffleNums[i];
                shuffleNums[i] = temp;
            }
            
            return shuffleNums;
        }
    }
    
    /**
     * 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();
     */
    

    相关文章

      网友评论

          本文标题:[LeetCode 384] Shuffle an Array

          本文链接:https://www.haomeiwen.com/subject/xgjqfctx.html