题目描述
输入一个长度为n的整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前面部分,所有的偶数位于数组的后面部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
数据范围:
0<=n<=5000
数组中每个数的值
0<=val<=10000
要求:时间复杂度O(n),空间复杂度O(n)
进阶:时间复杂度O(n^2),空间复杂度O(1)
示例1
输入:
[1,2,3,4]
返回:
[1,3,2,4]
示例2
输入:
[2,4,5,6,7]
返回:
[5,7,2,4,6]
示例3
输入:
[1,3,5,6,7]
返回:
[1,3,5,7,6]
思路
建立2个vector,一个按顺序存放奇数,一个按顺序存放偶数。从第一个数开始逐个读取,读取完成后依次输出2个数列。
具体实现
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int num = 0;
int total = 0;
int tempval = 0;
vector<int> odd,even;
vector<int>::iterator it;
string str;
string temp;
cout << "input e.g.[1,2,3,4]:" << endl;
cin>>str;
for(int i =0;i<str.length();i++)
{
if(str[i]==' ')
{
continue;
}
if(str[i]=='[')
{
continue;
}
if(str[i]==']')
{
tempval = atoi(temp.c_str());
if(tempval%2)
{
odd.push_back(tempval);
}
else{
even.push_back(tempval);
}
break;
}
if(str[i]==',')
{
tempval = atoi(temp.c_str());
if(tempval%2)
{
odd.push_back(tempval);
}
else{
even.push_back(tempval);
}
temp="";
continue;
}
temp += str[i];
}
cout<<"[";
for(it=odd.begin();it!=odd.end();it++)
{
cout<<*it<<",";
}
for(it=even.begin();it!=even.end();it++)
{
cout<<*it<<",";
}
cout<<"\b]"<<endl;
return 0;
}
时间复杂度
时间复杂度O(n),空间复杂度O(n)
小结
进阶难度:时间复杂度O(n^2),空间复杂度O(1),暂时没有想好实现方法,后续补上。