前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 905. Sort Array By Parity

LeetCode 905. Sort Array By Parity

作者头像
Angel_Kitty
发布2018-12-28 16:00:29
3480
发布2018-12-28 16:00:29
举报

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:

代码语言:javascript
复制
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 代码:

代码语言:javascript
复制
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++ 代码:

代码语言:javascript
复制
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;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-12-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 905. Sort Array By Parity
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档