描述
分割一个整数数组,使得奇数在前偶数在后。
您在真实的面试中是否遇到过这个题?
是
样例
给定 [1, 2, 3, 4]
,返回 [1, 3, 2, 4]
。
挑战
在原数组中完成,不使用额外空间。
这一题跟上一题非常像,稍微改一下就行,上一题见:https://blog.csdn.net/wenqiwenqi123/article/details/80795204
本题代码:
class Solution:
"""
@param: nums: an array of integers
@return: nothing
"""
def partitionArray(self, nums):
# write your code here
if (nums == None or len(nums) == 0): return nums
start, end = 0, len(nums) - 1
while (start < end):
while (start < end and nums[end]%2==0):
end -= 1
while (start < end and nums[start]%2==1):
start += 1
if (nums[start]%2==0 and nums[end]%2==1):
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
return nums
s=Solution()
print(s.partitionArray([1,2,3,4]))