leetcode-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:

1
2
3
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. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

分析


根据奇偶排序,偶数在前面,奇数在后面,顺序不重要。可以先将偶数筛选出来,再把奇数加在后面,如果是使用 Python 的列表推导的话,一行代码就可以了;也可以使用排序算法,自定义比较方法。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] result = new int[A.length];
int j = 0;
for (int i = 0; i < A.length; i++) {
if (A[i]%2 == 0) {
result[j] = A[i];
j++;
}
}
for (int i = 0; i < A.length; i++) {
if (A[i]%2 == 1) {
result[j] = A[i];
j++;
}
}
return result;
}
}

解决方案2(Python3)


1
2
3
4
5
6
7
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return [i for i in A if i%2 == 0] + [i for i in A if i%2 == 1]

解决方案3(Python3)


1
2
3
4
5
6
7
8
class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
A.sort(key=lambda x: x%2)
return A

题目来源