码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-07 14:29:12      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:tco   poi   point   href   sel   integer   turn   not   pytho   

题目描述:

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

样例

给定 [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

  

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

标签:tco   poi   point   href   sel   integer   turn   not   pytho   

原文地址:http://www.cnblogs.com/bozhou/p/6956270.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!