LeetCode 数组排序问题

给定一个非负整数数组 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] 也会被接受。	

长的代码是我自己写的:

class Solution:
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        odd = []
        even= []
        B = []
        for i in A:
            if i % 2 == 1:
                odd.append(i)
            else:
                even.append(i)
        for x,y in zip(odd,even):
            B.append(y)
            B.append(x)
        return B

短的是看别人写的(3种方法):

class Solution:
    def sortArrayByParityII(self, A):
        even, odd = [a for a in A if not a % 2], [a for a in A if a % 2]
        return [even.pop() if not i % 2 else odd.pop() for i in range(len(A))]

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        A.sort(key = lambda x : -(x % 2)) # sort odds in the front
        for i in range(0,len(A)/2,2): # pick even indexes to the middle of the list & swap values from front and back
            f = A[i]
            A[i], A[-(i+1)] = A[-(i+1)], f
        return A
        
class Solution:        
    def sortArrayByParityII(self, A):
        j = 0
        for i in range(len(A)):
            if A[i] % 2 == 0 and i % 2 != 0:
                while A[j] % 2 == 0:
                    j += 2
                A[i], A[j] = A[j], A[i]
        return A

猜你喜欢

转载自blog.csdn.net/weixin_43473360/article/details/83660917