zoukankan      html  css  js  c++  java
  • [leetcode]384. Shuffle an Array洗牌

    Shuffle a set of numbers without duplicates.

    Example:

    // Init an array with set 1, 2, and 3.
    int[] nums = {1,2,3};
    Solution solution = new Solution(nums);
    
    // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
    solution.shuffle();
    
    // Resets the array back to its original configuration [1,2,3].
    solution.reset();
    
    // Returns the random shuffling of array [1,2,3].
    solution.shuffle();

    题意:

    洗牌

    Solution1:

    code

     1 class Solution {
     2     int[] origin;
     3     int[] nums;
     4     Random random;
     5 
     6     public Solution(int[] nums) {
     7         origin = copy(nums);
     8         this.nums = copy(nums);
     9         random = new Random();
    10     }
    11 
    12     /** Resets the array to its original configuration and return it. */
    13     public int[] reset() {
    14         nums = copy(origin);
    15         random = new Random();
    16         return nums;
    17 
    18     }
    19 
    20     /** Returns a random shuffling of the array. */
    21     public int[] shuffle() {
    22         final int n = nums.length;
    23         int[] result = new int[n];
    24 
    25         for(int i = n; i>=1; i--){
    26             int randomIdx = random.nextInt(i);
    27             result[n - i] = nums[randomIdx];
    28             int temp = nums[randomIdx];
    29             nums[randomIdx] = nums[i - 1];
    30             nums[i - 1] = temp;
    31         }
    32         return result;
    33     }
    34 
    35     private int[] copy(int[] array){
    36         int[] result = new int[array.length];
    37         for(int i = 0; i < array.length; i++){
    38             result[i] = array[i];
    39         }
    40         return result;
    41     }
    42 }
    43 
    44 /**
    45  * Your Solution object will be instantiated and called as such:
    46  * Solution obj = new Solution(nums);
    47  * int[] param_1 = obj.reset();
    48  * int[] param_2 = obj.shuffle();
    49  */
  • 相关阅读:
    po教学001
    肖sir__ 金牌高级讲师__下载视频方法
    肖sir__ 金牌高级讲师__html下载收费音乐方法
    肖sir_少儿编程了解(001)
    【CF375D】Tree and Queries
    【CF1063F】String Journey
    【洛谷P6071】Treequery
    【ARC122E】Increasing LCMs
    【ARC122C】Calculator
    【牛客练习赛84 E】牛客推荐系统开发之标签重复度
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10823254.html
Copyright © 2011-2022 走看看