zoukankan      html  css  js  c++  java
  • LeetCode-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();

    Solution:
     1 public class Solution {
     2     int[] numArr;
     3 
     4     public Solution(int[] nums) {
     5         numArr = new int[nums.length];
     6         for (int i=0;i<nums.length;i++){
     7             numArr[i] = nums[i];
     8         }
     9     }
    10     
    11     /** Resets the array to its original configuration and return it. */
    12     public int[] reset() {
    13         return numArr;
    14     }
    15     
    16     /** Returns a random shuffling of the array. */
    17     public int[] shuffle() {
    18         int[] randArr = new int[numArr.length];
    19         for (int i=0;i<numArr.length;i++) randArr[i] = numArr[i];
    20         int last = numArr.length-1;
    21         Random engine = new Random();
    22         while (last>=0){
    23             int target = engine.nextInt(last+1);
    24             int temp = randArr[last];
    25             randArr[last] = randArr[target];
    26             randArr[target] = temp;
    27             last--;
    28         }
    29         return randArr;
    30     }
    31 }
    32 
    33 /**
    34  * Your Solution object will be instantiated and called as such:
    35  * Solution obj = new Solution(nums);
    36  * int[] param_1 = obj.reset();
    37  * int[] param_2 = obj.shuffle();
    38  */

  • 相关阅读:
    vj p1034题解
    2010.11.9南高模拟赛
    vj p1041神风堂人数 题解
    noi99钉子和小球 解题报告
    vj p1032题解
    vj p1037题解
    vj p1040题解
    vj p1038题解
    vj p1042捕风捉影 题解
    vj p1046 观光旅游 题解
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5779688.html
Copyright © 2011-2022 走看看