【LeetCode & 剑指offer刷题】发散思维题9:Shuffle an Array

【LeetCode & 剑指offer刷题】发散思维题9:Shuffle an Array

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

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

C++
 
//方法:洗牌算法 Fisher–Yates shuffle algorithm
//O(n),O(n)
#include <cstdlib>
#include <algorithm>
class Solution
{
private :
    vector < int > original ; //定义成员变量
    vector < int > array ;
public :
    Solution ( vector < int > nums ) //?这里为什么不用引用
    {
        srand ( time ( nullptr )); // 以当前时间为随机生成器的种子,这里要加,不加速度很慢(猜想可前没 能是如果rand()之 有srand,则每次都会运行srand(1)比较耗时)
        original = nums ; //这里为深拷贝
        array = nums ;
    }
   
    /** Resets the array to its original configuration and return it. */
    vector < int > reset ()
    {
        return original ;
    }
   
    /** Returns a random shuffling of the array. */
    vector < int > shuffle ()
    {
        int i , j ;
        for ( i = array . size ()- 1 ; i > 0 ; i --) //从后往前扫描
        {
            j = rand () % ( i + 1 ); //产生0~i的随机数(!!注意要产生0~i的随机数,而不是0~i-1,因为要包换不交换的情况)
            swap ( array [ i ], array [ j ]); //用当前数与随机选择的数进行交换
        }
        return array ;
    }
};
/*方法二:用stl中shuffle函数,如shuffle(v.begin(), v.end());
实现说明:rand() % (i+1) 实际上不准确,因为生成的数对于多数 i 值不均匀分布。正确实现将实际上需要重新实现 C++11 std::uniform_distributtion
*/
/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * vector<int> param_1 = obj.reset();
 * vector<int> param_2 = obj.shuffle();
 */
 
 

 

posted @ 2019-01-06 17:25 wikiwen 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值