输入一个长度为 n 整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前面部分,所有的偶数位于数组的后面部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
数据范围:
,数组中每个数的值
要求:时间复杂度
,空间复杂度
进阶:时间复杂度
,空间复杂度
[1,2,3,4]
[1,3,2,4]
[2,4,6,5,7]
[5,7,2,4,6]
[1,3,5,6,7]
[1,3,5,7,6]
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param array int整型一维数组 # @return int整型一维数组 # class Solution: def reOrderArray(self , array: List[int]) -> List[int]: # write code here a = [] b = [] for i in array: if i%2 == 0: a.append(i) if i%2 == 1: b.append(i) return b+a
class Solution: def reOrderArray(self , array: List[int]) -> List[int]: # write code here return [i for i in array if i%2==1]+[i for i in array if i%2==0]
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param array int整型一维数组 # @return int整型一维数组 # class Solution: def reOrderArray(self , array: List[int]) -> List[int]: res1 = [] res2 = [] for i in array: if i % 2 == 1: res1.append(i) else: res2.append(i) return res1 + res2
class Solution: def reOrderArray(self , array: List[int]) -> List[int]: # 边界情况 if len(array) == 0: return [] idx = 0 if self.checkIsEven(array[0]) else 1 for i in range(1, len(array)): if not self.checkIsEven(array[i]): # 分四段求和 array = array[:idx] + [array[i]] + array[idx:i] + array[i+1:] idx += 1 return array def checkIsEven(self, num): return num & 1 == 0
# 解法二:时间复杂度O(n^2),空间复杂度O(1) # 遍历数组,当遇到奇数且前一个数为偶数时交换两个数 class Solution: def reOrderArray(self , array: List[int]) -> List[int]: for i in range(1,len(array)): j=i while array[j]%2==1 and array[j-1]%2==0: array[j],array[j-1]=array[j-1],array[j] j-=1 return array # write code here
class Solution: def reOrderArray(self , array ): # write code here if array == []: return [] left = [] right = [] for i in range(len(array)): if array[i] & 1: left.append(array[i]) else: right.append(array[i]) return left + right