LintCode Python 简单级题目 373.奇偶分割数组

题目描述:

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

样例

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

挑战 

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

题目分析:

挑战 

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

新建两个指针,一个begin指向数组[0],一个end指向[n-1]
然后循环数组,找到一个偶数,与end交换
此时end[n-1]已为偶数,所有end重指向[n-2],

源码:

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

  

posted @ 2017-06-07 11:43  刘冬丶  阅读(903)  评论(0编辑  收藏  举报