首页 > 其他 > 详细

Partition Array by Odd and Even

时间:2016-08-07 12:30:19      阅读:218      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!