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


在编写代码时,我涉及到要把基本int类型的数组转换成list和把list转换成int[],但是在调用Arrays.asList()和List.toArray()方法时遇到了问题。值得注意的是这两个方法都是针对引用类型使用的,对于基本类型int,long,boolean等是存在问题的,具体的解决方法可以用引入额外的包函数Apache Commons Lang来解决或者使用Integer封装类型等方法。关于两者的区别可以参考一下文章:把Java数组转换为List时的注意事项;Convert list to array in Java - StackOverFlow;Array.asList:数组转list时你一定要知道的“陷阱”
代码如下:

class Solution {
    int[] nums;

    public Solution(int[] nums) {
        this.nums = new int[nums.length];
        for(int i = 0; i < nums.length; i++)
            this.nums[i] = nums[i];
    }

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

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        List<Integer> list = new ArrayList<>();
        for(int i : nums)
            list.add(i);
        int n = nums.length;
        Random random = new Random();
        int index;
        List<Integer> resList = new ArrayList<>();
        for(int i = n-1; i >=0; i--){
            index = random.nextInt(i+1);
            resList.add(list.remove(index));
        }
        int i = 0;
        int[] res = new int[n];
        for(Integer num : resList)
            res[i++] = num;
        return res;
    }
}

/**
 * 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();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值