zoukankan      html  css  js  c++  java
  • 384. Shuffle an Array(java,数组全排列,然后随机取)

    题目:

    Shuffle a set of numbers without duplicates.

    分析:

    对一组不包含重复元素的数组进行随机重排,reset方法返回最原始的数组,shuffle方法随机返回数组的一个排列,

    并且使得获得数组每一个排列的概率都是相同的。为此,可以在初始化时,求出数组的所有排列。在使用shuffle方法时,随机返回全排列中的一个。

    代码:

    public class Solution {
        
        //存储数组的所有排列
        List<int[]> list = new ArrayList<int[]>();
        public Solution(int[] nums) {
            //首先求所有排列
            permutations(nums,list,0);
        }
        
        /** Resets the array to its original configuration and return it. */
        public int[] reset() {
            return list.get(0);
        }
        
        /** Returns a random shuffling of the array. */
        public int[] shuffle() {
            int index = (int)(Math.random() * list.size());
            return list.get(index);
        }
        //求数组的所有排列
        public void permutations(int[] array,List<int[]> list,int start){
            if(array == null){
                return;
            }
            if(start == array.length){
                int[] temp = new int[array.length];
                System.arraycopy(array,0,temp,0,array.length);
                list.add(temp);
            }
            for(int i = start; i < array.length; ++i){
                swap(array,i,start);
                permutations(array,list,start+1);
                swap(array,i,start);
            }
        }
        //交换元素
        public void swap(int[] array,int i,int j){
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    /**
     * 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();
     */
  • 相关阅读:
    [saiku] 系统登录成功后查询Cubes
    216. Combination Sum III
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    211. Add and Search Word
    210. Course Schedule II
    分硬币问题
    开始学习Python
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5764780.html
Copyright © 2011-2022 走看看