Brush the problem -- adjust the order of the array so that the odd numbers come before the even numbers

Input an array of integers, implement a function to adjust the order of the numbers in the array, so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and ensure that odd and odd, even and even numbers are between The relative position remains unchanged.

If there is no last condition, we can solve this problem with ideas similar to quicksort.
I felt that I was limited by the idea of ​​quick sorting, and I always wanted to exchange, and then I wrote the following code.
The time complexity should reach O(N2).

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        p = 0
        even_number = []

        while p < len(array):
            if array[p] & 1 == 1:
                if even_number:
                    t = p

                    for i in range(len(even_number) - 1, -1, -1):
                        array[t] = array[t]^array[even_number[i]]
                        array[even_number[i]] = array[t]^array[even_number[i]]
                        array[t] = array[t]^array[even_number[i]]

                        t = t ^ even_number[i]
                        even_number[i] = t ^ even_number[i]
                        t = t ^ even_number[i]
            else:
                even_number.append(p)

            p += 1

        return array

The following code looks like the time complexity is O(N), but in fact, the process of remove is to move all the following elements forward by one.

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        i, p = 0, 0

        while i < len(array):
            if array[p] & 1 == 0:
                array.append(array[p])
                array.remove(array[p])
            else:
                p += 1

            i += 1

        return array

The following is an idea similar to insertion sort.

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        # write code here
        for i in range(len(array)):
            if array[i] & 1 == 1:
                temp = array[i]
                j = i - 1

                while (array[j] & 1 == 0) and j >= 0:
                        array[j + 1] = array[j]
                        j -= 1

                array[j + 1] = temp

        return array

An algorithm with a time complexity of O(N) may just traverse the array once, select odd and even numbers separately, and then combine them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326041631&siteId=291194637