905. Sort Array By Parity
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
解法
带参数的排序函数
class Solution:
def sortArrayByParity(self, A: 'List[int]') -> 'List[int]':
return sorted(A, key=lambda x: x % 2)
使用额外的列表
class Solution:
def sortArrayByParity(self, A: 'List[int]') -> 'List[int]':
return [x for x in A if x % 2 == 0] + [x for x in A if x % 2 == 1]
使用两根指针
class Solution:
def sortArrayByParity(self, A: 'List[int]') -> 'List[int]':
l, r = 0, len(A) - 1
while l < r:
if A[l] & 1:
A[l], A[r] = A[r], A[l]
l += not (A[l] & 1) # 偶数就加一
r -= A[r] & 1 # 奇数就减一
return A
小结
python 排序函数
A.sort(key=lambda x: x % 2)
>>> m = {'a': 1, 'c': 3, 'b': 2}
>>> sorted(m, key=lambda x: x[1])
[('a', 1), ('b', 2), ('c', 3)]
python 判断偶数的方法
# 取模
"odd" if num % 2 == 1 else "even"
# 位运算
"odd" if num & 1 else "even"
Last updated
Was this helpful?