首页 > 其他 > 详细

leetcode mock Shuffle an Array

时间:2016-10-08 01:56:14      阅读:206      评论:0      收藏:0      [点我收藏+]

1. shuffle算法:

http://www.cnblogs.com/huaping-audio/archive/2008/09/09/1287985.html

注意:我们一般用的是第二种swap的方法;但是第一种直接选择,然后把最末尾一位填上的方法,也是很好的。只是会需要两倍的空间。

 

2. Random nextInt(bound)参数表示 0-inclusive,bound-exclusive: [0, bound)

 

package com.company;


import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class Main {
    private int[] orig;

    public Main(int[] nums) {
        orig = nums;
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return orig;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] ret = orig.clone();
        Random rand = new Random();
        for (int i=0; i<ret.length; i++) {
            // int value between 0 (inclusive) and the specified value (exclusive)
            int r = rand.nextInt(ret.length-i);
            if (r != ret.length-i-1) {
                int k = ret[r];
                ret[r] = ret[ret.length - i - 1];
                ret[ret.length - i - 1] = k;
            }

        }
        return ret;
    }



    public static void main(String[] args) {
        // write your code here
        System.out.println("Hello");

        int []nums = {1,2,3};
        Main obj = new Main(nums);
        int[] param_1 = obj.reset();
        int[] param_2 = obj.shuffle();
        System.out.printf("param_1: %d, %d, %d\n", param_1[0], param_1[1], param_1[2]);
        System.out.printf("param_2: %d, %d, %d\n", param_2[0], param_2[1], param_2[2]);

    }
}

 

leetcode mock Shuffle an Array

原文:http://www.cnblogs.com/charlesblc/p/5936974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!