编程语言
首页 > 编程语言> > leetcode 922. Sort Array By Parity II(python)

leetcode 922. Sort Array By Parity II(python)

作者:互联网

描述

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Note:

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

解析

这里的题意比较简单,就是给出的 A 中有各有相等数量的奇数和偶数,然后按照 A[i] 是偶数, i 是偶数, A[i] 是奇数, i 是奇数的方式排列。结果只要满足规则即可。利用 list 的一些特殊使用技巧即可完成,时间复杂度是 O(N), 空间复杂度是 O(N),N 是 A 的长度。

解答

class Solution(object):
def sortArrayByParityII(self, A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    N = len(A)
    result = [None]*N
    result[::2] = [x for x in A if x%2==0]
    result[1::2] = [x for x in A if x%2==1]
    return result

运行结果

Runtime: 192 ms, faster than 77.50% of Python online submissions for Sort Array By Parity II.
Memory Usage: 14 MB, less than 32.79% of Python online submissions for Sort Array By Parity II.

解析

另外一种思路是利用 i 指针来找偶数,j 指针来找奇数。 让 A[i] 成为偶数,否则通过 j 来继续遍历数组来找到合适的数字进行交换。时间复杂度为 O(N),空间复杂度为 O(1),N 是 A 的长度。

解答

class Solution(object):
def sortArrayByParityII(self, A):
    """
    :type A: List[int]
    :rtype: List[int]
    """
    j = 1 
    for i in range(0, len(A), 2):
        if A[i]%2:
            while A[j]%2:
                j+=2
            A[i],A[j] = A[j],A[i]
    return A

运行结果

Runtime: 200 ms, faster than 53.23% of Python online submissions for Sort Array By Parity II.
Memory Usage: 13.8 MB, less than 76.98% of Python online submissions for Sort Array By Parity II.

标签:Sort,Parity,python,偶数,II,Array,submissions
来源: https://blog.csdn.net/wang7075202/article/details/111625574