码迷,mamicode.com
首页 > 其他好文 > 详细

Partition Array by Odd and Even

时间:2016-08-07 12:33:24      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

Partition an integers array into odd number first and even number second.

剑指offer的一道题,把所有奇数移动到偶数前面,其实是partition的双端解法,利用双指针。先检测两边合格的元素,都不合格,则交换,继续。

需要注意的是:

1.移动时,防止全部是偶数或者全部是奇数的情况,防止移动时越界。

2.交换时,仍然需要防止越界,全奇数或者全偶数,则left== right, 此时不应该交换。

3.注意判断奇偶时,利用位运算 &0x1(python 1)也可以。可以加速。

代码如下:

class Solution:
    # @param nums: a list of integers
    # @return: nothing
    def partitionArray(self, nums):
        if not nums or len(nums) == 1:
            return 
        left = 0
        right = len(nums) - 1
        while left < right:
            while left < right and nums[left] & 0x1 == 1:
                left += 1
            while left < right and nums[right] & 0x1 == 0:
                right -=1
            if left < right:
                nums[left],nums[right] = nums[right],nums[left]
                left += 1
                right -= 1
        
        return 

 

Partition Array by Odd and Even

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5745740.html

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