Article Directory
Without considering the relative position
Title Description
Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all of the odd part of the front half of the array, all the even located in the second half of the array.
analysis
Use 双指针
, the use of 快排
the 一次划分
idea, and soon get an answer.
Code
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
if not array:
return []
length = len(array)
left = 0
right = length-1
while left<right:
while left<right and not self.isEven(array[left]):
left += 1
while left<right and self.isEven(array[right]):
right -= 1
if left<right:
array[left], array[right] = array[right], array[left]
return array
def isEven(self, num):
return num & 1 == 0
Consider the relative position
Title Description
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.
analysis
- Method One: Using
python列表
the initialization list two eventually merged into the answers, time complexityO(n)
, space complexityO(n)
. - Method 2: Using the exchange of ideas on the topic, but can not be one
快排划分
, otherwise it can not be guaranteed to be the same relative position, so the idea of using the sort of exchange, the number two in the middle of the exchange to the number and relative numbers are exchanged位置不变
, the use of冒泡
thought.
Code
- method one:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
if not array:
return []
even = []
odd = []
for i in array:
if i & 1 == 1:
odd.append(i)
else:
even.append(i)
odd.extend(even)
return odd
- Method Two:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
if not array:
return []
length = len(array)
left = 0
while left < length:
# 寻找左边第一个偶数
while left < length and not self.isEven(array[left]):
left += 1
right = left+1
# 寻找此偶数后面的第一个奇数奇数
while right < length and self.isEven(array[right]):
right += 1
#按顺序排列交换
if left<length and right<length:
temp = array[right]
for i in range(right,left,-1):
array[i] = array[i-1]
array[left] = temp
if left<length and self.isEven(array[left]):
break
return array
def isEven(self, num):
return num & 1 == 0