【双指针】奇偶分割数组

思路:

两个指针,一个指头,一个指尾,当头指针位置小于尾指针时,若头指针指向的是偶数,而尾指针指向的是奇数,就把这两个指针指向的值互换。

要注意的点:

两个指针指向的值交换过后,一个往右,一个往左。

如果头指针指向的是奇数,头指针右移。如果尾指针指向的是偶数,尾指针左移。

Python实现:

class Solution:
    """
    @param: nums: an array of integers
    @return: nothing
    """
    def partitionArray(self, nums):
        # write your code here
        start, end = 0, len(nums)-1
        while start <= end:
            while start <= end and nums[start] % 2 == 1:
                start += 1 
            while start <= end and nums[end] % 2 == 0:
                end -= 1 
            if start <= end:
                nums[start], nums[end] = nums[end], nums[start]
                start += 1 
                end -= 1 
        
        return nums
posted @ 2020-04-14 10:35  アカツキ  阅读(204)  评论(0编辑  收藏  举报