LeetCode 905. Sort Array By Parity
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 <= 50000 <= A[i] <= 5000
题目描述:题意是要求给数组排序,排序的原则是偶数在前,奇数在后。
题目分析:很简单,我们直接给数组分分类就好了,然后用一个新的数组去存取值就行了。
python 代码:
class Solution(object):
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
odd_list = []
even_list = []
final_list = []
A_length = len(A)
for i in range(A_length):
if A[i] % 2 == 0:
even_list.append(A[i])
else:
odd_list.append(A[i])
final_list = even_list + odd_list
return final_list
C++ 代码:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
vector<int> final_list(A.size());
int count_odd = 0;
int count_even = 0;
for(int i = 0; i < A.size(); i++){
if(A[i] % 2 == 0){
count_even++;
}
else{
count_odd++;
}
}
vector<int> odd_list(count_odd);
vector<int> even_list(count_even);
int odd = 0;
int even = 0;
for(int i = 0; i < A.size(); i++){
if(A[i] % 2 == 0){
even_list[even++] = A[i];
}
else{
odd_list[odd++] = A[i];
}
}
final_list = even_list;
final_list.insert(final_list.end(),odd_list.begin(),odd_list.end());
return final_list;
}
};
作 者:Angel_Kitty
出 处:https://www.cnblogs.com/ECJTUACM-873284962/
关于作者:阿里云ACE,目前主要研究方向是Web安全漏洞以及反序列化。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
欢迎大家关注我的微信公众号IT老实人(IThonest),如果您觉得文章对您有很大的帮助,您可以考虑赏博主一杯咖啡以资鼓励,您的肯定将是我最大的动力。thx.
我的公众号是IT老实人(IThonest),一个有故事的公众号,欢迎大家来这里讨论,共同进步,不断学习才能不断进步。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码),个人QQ和微信的二维码也已给出,扫描下面👇的二维码一起来讨论吧!!!
欢迎大家关注我的Github,一些文章的备份和平常做的一些项目会存放在这里。

浙公网安备 33010602011771号