版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuxuemingzhu/article/details/83045735
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/sort-array-by-parity-ii
题目描述:
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
题目大意
把一个数组重新排序,使得偶数位置全是偶数,奇数位置全是奇数。
解题方法
直接使用两个数组分别存放奇数和偶数,然后结果就是在这两个里面来回的选取就好了。这种做法比较简单,打比赛比较适用。
时间复杂度是O(N),空间复杂度是O(N)。
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
odd = [x for x in A if x % 2 == 1]
even = [x for x in A if x % 2 == 0]
res = []
iseven = True
while odd or even:
if iseven:
res.append(even.pop())
else:
res.append(odd.pop())
iseven = not iseven
return res
参考资料:
日期
2018 年 10 月 14 日 —— 周赛做出来3个题,开心