当前位置:网站首页>Sword finger offer 21 Adjust array order so that odd numbers precede even numbers
Sword finger offer 21 Adjust array order so that odd numbers precede even numbers
2022-06-11 08:43:00 【zmm_ mohua】
The finger of the sword Offer 21. Adjust the array order so that the odd Numbers precede the even Numbers
subject

Code
#include <iostream>
#include <vector>
using namespace std;
// Method 1 : Time limit exceeded
vector<int> exchange1(vector<int>& nums) {
int n = nums.size();
if(n == 0 || n == 1){
return nums;
}
for(int i = 0; i < n - 1; i++){
if(nums[i] % 2 == 1){
continue;
}
for(int j = i + 1; j < n; j++){
if(nums[j] % 2 == 1){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
break;
}
}
}
return nums;
}
// Method 2 : Using the array , Odd number from to save , Even numbers are saved from back to front
vector<int> exchange(vector<int>& nums) {
int n = nums.size();
if(n == 0 || n == 1){
return nums;
}
vector<int> res (n);
int j = 0, k = n - 1;
for(int i = 0; i < n; i++){
if(nums[i] % 2 == 1){
res[j++] = nums[i];
}else{
res[k--] = nums[i];
}
}
return res;
}
int main(){
int n;
cin>>n;
vector<int> nums(n);
vector<int> res;
for(int i = 0; i < n; i++){
cin>>nums[i];
}
res = exchange(nums);
for(int i = 0; i < res.size(); i++){
cout<<res[i]<<" ";
}
return 0;
}
边栏推荐
- Jupyter notebook code completion plug-in + Solution
- Codeworks round 723 (Div. 2)
- BFS on tree (tree breathing first search)
- 补2:圆环回原点问题
- (resolved) pychart debug error -unicode decodeerror: 'UTF-8' codec can't decode byte 0xe8 in position 1023
- [programming development] markdown notes tutorial
- 盘它!用「飞项」轻松管理各类型项目
- Js学习基础document.write在页面中写一行文字
- uniapp 插件开发
- 剑指 Offer 62. 圆圈中最后剩下的数字
猜你喜欢

Is the result too different from the goal? With the help of target management, you can reach the target accurately!

进程间的通信

Difference between threadpooltaskexecutor and ThreadPoolExecutor

torch. roll

MySQL advanced features, you can read more about it and meet the interview

torch. Var (), sample variance, parent variance

Implementation of CRF for named entity recognition

Web design and website planning assignment 14 add background music to the video

ActiveMQ简单教程,适合初学者,学习笔记yyds

qiao-npms:获取npm包下载量
随机推荐
Js基础学习Script
不想项目失控?你需要用对项目管理工具
Pypharm startup is stuck, loading project
GO语言:字符串的连接、数字转化字符串
ActiveMQ简单教程,适合初学者,学习笔记yyds
剑指 Offer 51. 数组中的逆序对
剑指 Offer 62. 圆圈中最后剩下的数字
uniapp关闭/开启/调节系统声音
AttributeError: module ‘tensorflow. compat. v2.__ internal__‘ has no attribute ‘register_ clear_ session_
知识图谱入门之---yedda标注
The difference between & & and &
The difference between equals and = =
剑指 Offer 40. 最小的k个数
Pg/oracle database ASCII code to string custom function
Uniapp plug-in development
进程间的通信
项目实训-克隆门
Matlab学习7-图像处理之线性平滑滤波
Interprocess communication
(taking pytorch as an example) a simple understanding of the regularization method of path (depth) -drop path