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

p105 打乱数组(leetcode 384)

时间:2020-04-08 18:48:48      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:new   res   amp   and   java   vat   tor   set   tco   

一:解题思路

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
private:
    vector<int> nums;
    vector<int> orignalNums;
public:
    Solution(vector<int>& nums) 
    {
        this->nums = nums;
        this->orignalNums = nums;
    }

    vector<int> reset() 
    {
        return this->orignalNums;
    }

    vector<int> shuffle() 
    {
        for (int i = nums.size() - 1; i >= 0; i--)
        {
            int j = rand() % (i+1);
            swap(nums[i],nums[j]);
        }

        return nums;
    }
};

Java:

class Solution {
        private Random rnd=new Random();
        private int[] nums;
        private int[] orignalNums;
        
        private void swap(int[] nums,int i,int j)
        {
            int temp=nums[i];
            nums[i]=nums[j];
            nums[j]=temp;
        }
        
        public Solution(int[] nums)
        {
              this.nums=nums;
              this.orignalNums=Arrays.copyOf(nums,nums.length);
        }


        public int[] reset() 
        {
               return this.orignalNums;
        }

        public int[] shuffle() 
        {
               for(int i=nums.length-1;i>=0;i--)
               {
                   int j=rnd.nextInt(i+1);
                   swap(nums,i,j);
               }
               
               return nums;
        }
    }

 

p105 打乱数组(leetcode 384)

标签:new   res   amp   and   java   vat   tor   set   tco   

原文地址:https://www.cnblogs.com/repinkply/p/12661531.html

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