C-LeetCode-Shuffle an Array跑不过测试用例

使用time()作为随机数种子,一秒改变一次随机数还是不够随机,跑不过测试用例6
,在加上个毫秒级计时精度的clock()作为随机数种子就达标了。

示例代码:

typedef struct {
    int* ori_nums;
    int* shu_nums;
    int size;
} Solution;

Solution* solutionCreate(int* nums, int size) {
    // 这里创建Solution sol;返回return /会有问题。。
    Solution *sol;
    sol = malloc(sizeof(Solution));
    sol->ori_nums = malloc(size * sizeof(int));
    sol->shu_nums = malloc(size * sizeof(int));
    for(int i=0; i<size; ++i){
        sol->ori_nums[i] = nums[i];
        sol->shu_nums[i] = nums[i];
    }
    sol->size = size;
    return sol;
}

/** Resets the array to its original configuration and return it. */
int* solutionReset(Solution* obj, int *returnSize) {
    //for(int i=0; i<obj->size; ++i){
    //    obj->shu_nums[i] = obj->ori_nums[i];
    //}
    *returnSize = obj->size;
    return obj->ori_nums;
}

/** Returns a random shuffling of the array. */
int* solutionShuffle(Solution* obj, int *returnSize) {
    int r_temp, temp;
    /**
        srand(time(NULL))一秒一个随机数还是不够随机,跑不过测试用例6
        printf("%d,%d\n", time(NULL),clock());
    */
    srand(time(NULL) + clock());//设置随机数种子。
    
    for(int i=obj->size; i>0; --i){
        //ISO IEC 9899 2011 (C11)标准中未规定 RAND_MAX 的具体数值。但该标准规定了RAND_MAX 的值应至少为32767。
        r_temp = rand()%i;
        temp = obj->shu_nums[r_temp];
        obj->shu_nums[r_temp] = obj->shu_nums[i-1];
        obj->shu_nums[i-1] = temp;
    }
    *returnSize = obj->size;
    return obj->shu_nums;
}

void solutionFree(Solution* obj) {
    free(obj->ori_nums);
    free(obj->shu_nums);
    free(obj);
}

/**
 * Your Solution struct will be instantiated and called as such:
 * struct Solution* obj = solutionCreate(nums, size);
 * int* param_1 = solutionReset(obj);
 * int* param_2 = solutionShuffle(obj);
 * solutionFree(obj);
 */

猜你喜欢

转载自www.cnblogs.com/jffun-blog/p/9070172.html