码迷,mamicode.com
首页 > 编程语言 > 详细

384. Shuffle and Array(java,数组全排列,然后随机取)

时间:2016-08-12 14:57:42      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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();
 */

 

384. Shuffle and Array(java,数组全排列,然后随机取)

标签:

原文地址:http://www.cnblogs.com/mydesky2012/p/5764780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!