数组排序

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

def sortArrayByParityII(list):
    t1 = []
    t2 = []
    for num in list:
        if num%2 == 0:
            t2.append(num)
        else:
            t1.append(num)
    t1.sort()
    t2.sort()
    res = [0 for _ in range(len(list))]
    for i in range(0,len(list),2):
        res[i] = (t1[i//2])
        res[i+1] = (t2[(i // 2)])
    print(res)
    return res


if __name__ == '__main__':
    list = [4, 8, 3, 2, 1, 9, 7, 6]
    sortArrayByParityII(list)

结果:
数组排序_第1张图片

你可能感兴趣的:(编程demo)