1 //一种O(n)的洗牌算法 2 vector<int> randNUms(vector<int> &nums, int m) 3 { 4 int len = nums.size(); 5 if (len < m) 6 return {}; 7 8 vector<int> res; 9 for (int i = len - 1; i >= 0, m-- > 0; i--) 10 { 11 int r = rand() % i; 12 res.push_back(nums[r]); 13 int tmp = nums[r]; 14 nums[r] = nums[i]; 15 nums[i] = tmp; 16 } 17 return res; 18 }
时间O(n),空间O(1).