您的位置:首页 > 其它

lintcode 容易题:Partition Array by Odd and Even 奇偶分割数组

2015-10-12 19:55 232 查看
题目:

奇偶分割数组

分割一个整数数组,使得奇数在前偶数在后。

样例

给定
[1, 2, 3, 4]
,返回
[1, 3, 2, 4]


挑战

在原数组中完成,不使用额外空间。

解题:

一次快速排序就可以得到结果

Java程序:

class Solution:
# @param nums: a list of integers
# @return: nothing
def partitionArray(self, nums):
# write your code here
left = 0
right = len(nums) - 1
while left<right:
tmp = nums[left]
while left<right and nums[right]%2==0:
right-=1
if left<right:
nums[left] = nums[right]
left +=1
while left<right and nums[left]%2==1:
left+=1
if left<right:
nums[right] = nums[left]
right-=1
nums[left] = tmp


View Code
总耗时: 408 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: