题目
给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。
你可以返回满足此条件的任何数组作为答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例
输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
提示:
1 <= A.length <= 5000
0 <= A[i] <= 5000
解题
最笨的办法,遍历数组A,把偶数放在偶数列表中,奇数放在奇数列表中,遍历完成后,把奇数列表追加到偶数列表后。
class Solution:
def sortArrayByParity(self, A):
oushu = []
jishu = []
for i in A:
if i % 2 == 0:
oushu.append(i)
else:
jishu.append(i)
for i in jishu:
oushu.append(i)
return oushu
使用双指针的解法
class Solution:
def sortArrayByParity(self, A):
left_index = 0
right_index = 1
while right_index < len(A):
if A[left_index] % 2 == 0:
left_index += 1
right_index += 1
else:
if A[right_index] % 2 != 0:
right_index += 1
else:
A[left_index], A[right_index] = A[right_index], A[left_index]
left_index += 1
right_index += 1
return A