LeetCode 922. 按奇偶排序数组 II

题目来源:https://leetcode-cn.com/problems/sort-array-by-parity-ii/

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。

示例:

输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。

提示:

2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000

思路:
由于没有规定返回数组的顺序,一个很自然的想法就是开输入数组长度的空间,遍历给定数组,再根据是奇数还是偶数按顺序赋值。时间复杂度和空间复杂度都是O(n)。

class Solution:
    def sortArrayByParityII(self, A: List[int]) -> List[int]:
        nums = [0] * len(A)
        oddIndex = 1
        evenIndex = 0
        for i in range(len(A)):
            if A[i] % 2 == 0:
                nums[evenIndex] = A[i]
                evenIndex += 2
            else:
                nums[oddIndex] = A[i]                
                oddIndex += 2
        return nums

一个更简单的思路是用双指针遍历数组,遇到满足条件的数字跳过,直到两个指针都遇到不满足条件的数字,然后交换这两个数,继续遍历。这样做不需要创建额外空间。

class Solution:
    def sortArrayByParityII(self, A: List[int]) -> List[int]:
        i = 0
        j = 1
        while True:
            while i < len(A) and A[i] % 2 == 0:
                i += 2
            while j < len(A) and A[j] % 2 == 1:
                j += 2
            if i <= len(A) and j <= len(A):
                A[i], A[j] = A[j], A[i]
                i += 2
                j += 2
            else:
                return A

你可能感兴趣的:(LeetCode 922. 按奇偶排序数组 II)