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  */
  • 相关阅读:
    ajax同步和异步
    vue组件
    type of的返回值有哪些
    git配置
    vue 获取时间戳对象转换为日期格式
    JavaScript运行机制
    单页面开发首屏加载慢,白屏如何解决
    单页面和多页面开发的优缺点
    【安全测试】sql注入
    【Python学习一】使用Python+selenium实现第一个自动化测试脚本
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10823254.html
Copyright © 2011-2022 走看看