Leetcode 每日一题
题目链接: 922. 按奇偶排序数组 II
难度: 简单
解题思路: 先桶排序一下,可以统计每个元素的出现的次数和他的奇偶性。然后再按照奇偶性填入原数组。
题解:
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
length = len(A)
bucket = [0] * 1001
bucket_len = 0
# 桶排序
for example in A:
bucket[example] += 1
bucket_len = max(bucket_len, example)
bucket_index = 0
A_index = 0
# 偶数
while A_index < length and bucket_index <= bucket_len:
if bucket[bucket_index] != 0:
A[A_index] = bucket_index
bucket[bucket_index] -= 1
A_index += 2
else:
bucket_index += 2
bucket_index = 1
A_index = 1
# 奇数
while A_index < length and bucket_index <= bucket_len:
if bucket[bucket_index] != 0:
A[A_index] = bucket_index
bucket[bucket_index] -= 1
A_index += 2
else:
bucket_index += 2
return A