当前位置:网站首页>剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
2022-06-11 08:28:00 【zmm_mohua】
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
题目

代码
#include <iostream>
#include <vector>
using namespace std;
// 方法一:超出时间限制
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;
}
// 方法二:利用数组,奇数从前往后存,偶数从后往前存
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;
}
边栏推荐
- Installing MySQL and cluster operation on virtual machine in Linux system
- Empty difference between postgrepsql and Oracle
- Solution to the occurrence interval (space) of latex manual numbering documents
- Typescript enumeration
- torch. nn. functional. pad
- How to solve the MySQL deadlock problem? Recitation version
- DAMENG 数据库启停
- Solve valueerror: no model found in config file
- (二)从架构设计角度分析AAC源码-我的LiveData
- How CSDN reports plagiarized articles
猜你喜欢

Redis cluster in Linux system
![[software tool] the hacker matrix special effect software CMatrix](/img/d3/bbaa3dfd244a37f0f8c6227db37257.jpg)
[software tool] the hacker matrix special effect software CMatrix

BFS on tree (tree breathing first search)

Idea annotation settings

结果和目标出入太大?不妨借助目标管理精准直达目标!

node报错整理

Node error report sorting

Record a murder case caused by ignoring the @suppresslint ("newapi") prompt

Deep understanding of add in argparse module_ Argument parameters (such as action)

go for it Easily manage all types of items with "flying items"
随机推荐
node报错整理
In an activity, view postdelay will cause memory leakage, but will not affect the life cycle execution of the activity.
Using flying items to manage by objectives, not being a "headless fly" in the workplace
In place reversal of a LinkedList
Idea annotation settings
Idea pulls items from remote warehouse
进程间的通信
Typescript unknown type
[software tools] screen recording software captura
一些学习记录i=
Zookepper===> animal management system
指定环境下安装Jupyter
Icml2022 article intéressant
ICML2022有意思的文章
Difference between threadpooltaskexecutor and ThreadPoolExecutor
Don't want the project out of control? You need to use project management tools
What does it mean to buy a single-mode, dual-mode and Rechargeable Wireless Mouse
Typescript declaration merge
Typescript class and interface, class and generic, interface merging
Solution to the occurrence interval (space) of latex manual numbering documents