当前位置:网站首页>384.打乱数组
384.打乱数组
2022-07-30 05:38:00 【Linke66】


解题思路:
用一个辅助数组vec,大小与传入数组一样,并且元素是生成的随机数。使得vec按照升序排序,并且原始数组也按照其排序方法排序。通过这种方式来随机打乱数组。
举个例子:
nums [2,3,1] vec [10,6,30]
那么vec按升序排序就是vec[0]和vec[1]交换,那么nums[0]和nums[1]也交换。所以
nums [3,2,1] vec [6,10,30]
具体代码如下
class Solution {
vector<int> m_nums; //初始数组
vector<int> n_nums; //用来操作的数组
vector<int> vec;
public:
Solution(vector<int>& nums) {
for(int i=0;i<nums.size();++i)
m_nums.push_back(nums[i]);
//调制大小
n_nums.resize(nums.size());
vec.resize(nums.size());
}
vector<int> reset() {
return m_nums;
}
vector<int> shuffle() {
int n=m_nums.size();
//生成[0-199]的随机数,范围无所谓
for(int i=0;i<n;++i)
vec[i]=rand()%200;
//拷贝原始数组
for(int i=0;i<n;++i)
n_nums[i]=m_nums[i];
//使用冒泡排序使得vec按升序排序
for(int i=0;i<n;++i){
for(int j=0;j<n-i-1;++j){
if(vec[j]>vec[j+1]){
swap(vec[j],vec[j+1]);
swap(n_nums[j],n_nums[j+1]); //n_nums也按照相同的规则排序,即打乱
}
}
}
return n_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(); */
边栏推荐
- navicat连接MySQL报错:1045 - Access denied for user ‘root‘@‘localhost‘ (using password YES)
- MySQL stored procedure
- Introduction to Oracle Patch System and Opatch Tool
- Learn FPGA from the underlying structure (6) ---- Distributed RAM (DRAM, Distributed RAM)
- Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
- 839. 模拟堆
- 2022年比若依更香的开源项目
- 【Koltin Flow(一)】五种创建flow的方式
- 【图像处理】基于中轴变换实现图像骨架提取附matlab代码
- list(列表)和array(数组)的区别
猜你喜欢
随机推荐
Programmers make money and practice, teach you how to do paid courses, self-media, paid articles and paid technical courses to make money
2022年比若依更香的开源项目
Error: npm ERR code EPERM
839. 模拟堆
cmd (command line) to operate or connect to the mysql database, and to create databases and tables
MySQL (2)
75. 颜色分类
Teach you how to design a CSDN system
MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法
idea 编译protobuf 文件的设置使用
[GStreamer] 插件的名字要和GST_PLUGIN_DEFINE匹配
4461. 范围分区(Google Kickstart2022 Round C Problem B)
Solve phpstudy unable to start MySQL service
It's time to have to learn English, give yourself multiple paths
MySQL stored procedure
Personal blog system (with source code)
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
numpy中np.inf函数的用法讲解
MySQL的 DDL和DML和DQL的基本语法
net start mysql MySQL 服务正在启动 . MySQL 服务无法启动。 服务没有报告任何错误。









