【leetcode】922. Sort Array By Parity II

题目如下:

解题思路:非常简单的题目,引入两个变量oddInx = 1和evenInx = 0,和与A等长的结果数组res。然后遍历A,如果A[i]为偶数,则令res[evenInx] = A[i],evenInx += 2;否则令res[oddInx] = A[i],evenInx += 2。

代码如下:

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        res = [0] * len(A)
        oddInx = 1
        evenInx = 0
        for i in A:
            if i % 2 == 0:
                res[evenInx] = i
                evenInx += 2
            else:
                res[oddInx] = i
                oddInx += 2 
        return res

 

posted @ 2018-10-16 10:16  seyjs  阅读(323)  评论(0编辑  收藏  举报