The title description enters an array of integers, implements a function to adjust the order of the numbers in the array, so that all the odd digits are placed in the first half of the array, all the even digits are located in the second half of the array, and the relative positions between the odd and odd, even and even are guaranteed. Thinking of solving problems
Time To change space:
Thought can refer to insert sort. Time complexity O (n^2), Space complexity O (1)
Class Solution {public: void Reorderarray (vector<int> &array) { int i,j; int tmp; For (I=0;i<array.size (); i++) { tmp=array[i]; j=i-1; if (array[i]%2==1) { while (j>=0&&array[j]%2==0) { array[j+1]=array[j]; j--; } array[j+1]=tmp;}}} ;
Similarly, it is possible to solve this problem with a quick-line idea.
Space-changing time:
Link: https://www.nowcoder.com/questionTerminal/beb5aa231adc45b2a5dcc5b62c93f593 Source: Cattle net//second idea: Create an array class again Solution{public: void Reorderarray (vector<int> &array) { vector<int> array_temp; Vector<int>::iterator ib1, ie1; ib1 = Array.begin (); for (; IB1! = Array.end ();) { //Meet even, save to new array and delete from original array if (*ib1% 2 = = 0) { array_temp.push_back (*IB1); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IB1 = Array.erase (IB1); } else{ ib1++; } } vector<int>::iterator Ib2, ie2; &NBSP;&NBSP;&NBSP;IB2 = Array_temp.begin (); ie2 = Array_temp.end (); for (; Ib2! = Ie2; ib2++) //Add the number of new arrays to the old array { array.push_back (*IB2); } }};
The second idea of optimization:
Instead of deleting even numbers, deleting even numbers in an array brings additional overhead, records the even-numbered locations, and then overwrites the next cardinality directly over the past!
Sword offer-Adjust array inside odd even order