Prove safety arrays offer adjustment sequence is located in front of the even-odd

1. Topic

Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all the odd part of the front half of the array, is located in the second half of all the even array, and between odd and ensure a relatively even, odd and even the same position.

Source: prove safety offer
links: https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&tqId=11166&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

2. My problem solution

(1) there is a stable sort insertion sort, bubble sort, merge sort, sorting algorithm can learn to solve this problem.
Time complexity: O(n^2)
the spatial complexity: O(1)
(2) an auxiliary array, the first traversal over the original array, extraction into an auxiliary array of odd order, then traverse again the original array, are extracted into the even order secondary array, and finally the auxiliary array assignment to the original array.
Time complexity: O(n)
space complexity:O(n)

To copy data to a secondary array and then change the value of the original array, or to change the value of the auxiliary array and then copied to the original array, it is the same.

class Solution {
public:
    void reOrderArray(vector<int> &array) {
        vector<int> vec(array.begin(),array.end());
        int num=0;
        for(int i=0;i<array.size();i++)
            if(vec[i]&1)array[num++]=vec[i];
        for(int i=0;i<array.size();i++)
            if((vec[i]&1)==0)array[num++]=vec[i];
    }
};

3. someone else's problem solution

4. Summary and Reflection

(1) (vec[i]&1)==0and vec[i]&1==0what is the difference? do not forget.
(2) If no guarantee relative order of elements may be used in quick sort partitionoperation.

Published 32 original articles · won praise 0 · Views 416

Guess you like

Origin blog.csdn.net/weixin_43951240/article/details/103948774