[cpp] view plaincopyprint?
/*
给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。
要求:空间复杂度O(1),时间复杂度为O(n)。
//*/
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
void swap_int(int& a, int& b)
{
int t = a;
a = b;
b = t;
}
int main()
{
int numel[] = {1, 23, 2, 34, 21, 45, 26, 22, 41, 66, 74, 91, 17, 64};
int sz = sizeof(numel)/sizeof(numel[0]);
for(int i =0; i<sz; ++i){
cout << numel[i] << " ";
}
cout << endl;
int begin = 0;
int end = sz -1;
while(begin < end){
while(numel[begin]%2 == 1 && end > begin){
++begin;
}
while(numel[end]%2 == 0 && end > begin){
--end;
}
swap_int(numel[begin], numel[end]);
}
for(int i =0; i<sz; ++i){
cout << numel[i] << " ";
}
cout << endl;
return 0;
}
给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数
最新推荐文章于 2016-06-25 16:57:52 发布
本文介绍了一种方法,通过遍历数组并使用双指针技巧,实现将数组中奇数元素置于左侧,偶数元素置于右侧的操作,同时确保算法的时间复杂度为O(n)且空间复杂度为O(1)。
5268

被折叠的 条评论
为什么被折叠?



