#不能满足奇数和偶数相对位置不变的条件。
class Solution:
def reOrderArray(self, array):
if not array:return
begin, end = 0, len(array)-1
while begin < end:
while begin < end and array[begin] % 2 != 0:
begin += 1
while begin < end and array[end] % 2 == 0:
end -= 1
if begin < end:
tmp = array[begin]
array[begin] = array[end]
array[end] = tmp
return array
Python题解二(高级解法)
#仍然不满足条件,但是可扩展性较高
class Solution:
def reOrderArray(self, array):
def isEven(n):
return (n % 2) == 0
def reOrder(array, func):
if not array:return
begin, end = 0, len(array)-1
while begin < end:
while begin < end and not func(array[begin]):
begin += 1
while begin < end and func(array[end]):
end -= 1
if begin < end:
tmp = array[begin]
array[begin] = array[end]
array[end] = tmp
return array
return reOrder(array, isEven)
Python题解三(究级解法)
#
class Solution:
def reOrderArray(self, array):
def isEven(n):
return not (n % 2) == 0
def reOrder(array, func):
if not array: return []
i, j = 0, 0
while i < len(array):
while i < len(array) and func(array[i]):#奇数就跳过
i += 1
j = i + 1
while j < len(array) and not func(array[j]):#偶数就跳过
j += 1
if j < len(array):
tmp = array[j]
for k in range(j - 1, i-1, -1):
array[k + 1] = array[k]
array[i] = tmp
i += 1
else:
break
return array
return reOrder(array, isEven)
考点