标签:array order tor push scribe 思路 vector 实现 iter
class Solution { public: void reOrderArray(vector<int> &array) { vector<int> a,b; for(int i=0;i<array.size();i++) { if(array[i]%2==1) a.push_back(array[i]); else b.push_back(array[i]); } for(int j=0;j<b.size();j++) a[a.size()-1+j]=b[j]; } };
超时,溢出了!
改进一下代码,如下。
class Solution { public: void reOrderArray(vector<int> &array) { vector<int> b; vector<int>::iterator ib; for(ib=array.begin();ib!=array.end();) { if(*ib%2==0) { b.push_back(*ib); ib=array.erase(ib); } else ib++; } vector<int> ::iterator ib2=b.begin(); for(ib2;ib2!=b.end();ib2++) { array.push_back(*ib2); } } };
碰到另外一种思路:
思路:类似冒泡算法,前偶后奇数就交换: class Solution { public: void reOrderArray(vector<int> &array) { for (int i = 0; i < array.size();i++) { for (int j = array.size() - 1; j>i;j--) { if (array[j] % 2 == 1 && array[j - 1]%2 == 0) //前偶后奇交换 { swap(array[j], array[j-1]); } } } } };
标签:array order tor push scribe 思路 vector 实现 iter
原文地址:http://www.cnblogs.com/dd2hm/p/7290514.html