384. 打乱数组 ( 随机)

  题目连接:

https://leetcode-cn.com/problems/shuffle-an-array/

题目大意:

中文题目,自己读

具体思路:

主要是记录如何进行随机化,以及如何使用this指针   assign函数和直接赋值效率是差不多的

AC代码:

class Solution {
public:
    
    vector<int>co;
    vector<int>nums;
    
    Solution(vector<int>& nums) {
    
        this->nums = nums;
        this->co = nums ;
        
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        
        nums.clear();
        nums = co;
    //    nums.assign(co.begin() , co.end());
        
        return this->nums;
        
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        
        int i , len ;
        len = nums.size(); 
        if(len == 0) return nums;
        
        for( i = 0 ;i < len ; i++){
        
            int x = rand() % len;
            swap(nums[i] , nums[x]);
        }
      return nums;
    }
};

/**
 * 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-09-02 16:00  Let_Life_Stop  阅读(216)  评论(0编辑  收藏  举报