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.
给定一个非负整数数组A,请返回一个数组,这个数组的前面是A中的偶数,偶数后面跟着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、1 <= A.length <= 5000
2、0 <= A[i] <= 5000
【Leetcode_Array --905. Sort Array By Parity [easy]】Solutions:
Pythonclass Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""even,odd = [],[]
for i in A:
if i%2 == 0:
even.append(i)
else:
odd.append(i)
return even+odd
C++class Solution {
public:
vector sortArrayByParity(vector& A) {
vector even;
vector odd;
for (int i : A){
if (i%2 == 0){
even.push_back(i);
}
else{
odd.push_back(i);
}
}
even.insert(even.end(),odd.begin(),odd.end());
#在vector even后面插入vector odd;even.insert(even.begin(),odd,begin(),odd.end())为在even前面插入odd
return even;
}
};
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- Python|Python Leetcode(665.非递减数列)