题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
两种方法:
第一种,使用排序方法,我感觉这里考察的是对常见排序算法的理解,下面使用插入和冒泡两种排序思想实现:
插入:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
Oindex=0
Eindex=len(array)-1
for i in range(len(array)):
if array[i]%2==0:
if i<Eindex:
Eindex=i
else:
continue
else:
if i>Eindex:
Temp=array[i]
array.pop(i)
array.insert(Eindex,Temp)
Eindex+=1
else:
continue
return array
冒泡:
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
count = 0
for i in range(0,len(array)):
for j in range(len(array)-1,i,-1):
if array[j-1]%2 ==0 and array[j]%2==1:
temp = array[j-1]
array[j-1] = array[j]
array[j] = temp
return array
第二种方法:
思路很简单,就是把数组里面的奇数和偶数分开存储,然后将偶数列表append进奇数列表里面。
# -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
OddList=[]
EvenList=[]
for i in range(len(array)):
if array[i]%2==1:
OddList.append(array[i])
else:
EvenList.append(array[i])
OddList.extend(EvenList)
return OddList
参考文献:
https://www.nowcoder.com/profile/829145/codeBookDetail?submissionId=12656585