leetcode-922 按奇偶排序数组 II

leetcode-922 按奇偶排序数组 II

题目描述:

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

解法一:

class Solution:
    def sortArrayByParityII(self, A: List[int]) -> List[int]:
        i,j = 0,0
        n = len(A)
        indx = 0
        while i < n and j<n:
            while j<n and A[j]%2 == 1:
                j += 1
            while i < n and A[i]%2 == 0:
                i += 1
            if indx % 2 == 0:
                A[indx],A[j] = A[j], A[indx]
                indx += 1
                j += 1
            else:
                A[indx],A[i] = A[i], A[indx]
                indx += 1
                i += 1
        return A
原文地址:https://www.cnblogs.com/curtisxiao/p/11241766.html