博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 905. Sort Array By Parity
阅读量:7052 次
发布时间:2019-06-28

本文共 1897 字,大约阅读时间需要 6 分钟。

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. 1 <= A.length <= 5000
  2. 0 <= 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
sortArrayByParity(vector
& A) { vector
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
odd_list(count_odd); vector
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; }};

转载于:https://www.cnblogs.com/ECJTUACM-873284962/p/10162828.html

你可能感兴趣的文章
关于AppCompatAutoCompleteTextView使用总结
查看>>
上网搜了很多JQuery树型表格插件都不满意,决定自己写
查看>>
最新Django2.0.1在线教育零基础到上线教程(七)-7-完结
查看>>
彻底解决mysql中文乱码
查看>>
简单优化前端工程几种方式(上篇)
查看>>
Spring Cloud Spring Boot mybatis分布式微服务云架构(十二)返回JSON格式
查看>>
Python全栈 MongoDB 数据库(Mongo、 正则基础、一篇通)
查看>>
react native 开发常用优质第三方组件
查看>>
C# 操作Word文本框——插入表格/读取表格/删除表格
查看>>
Mybatis-Generator_学习_02_使用Mapper专用的MyBatis Generator插件
查看>>
云栖大会首设“科技脱贫”专场 ,20张会场门票等你来拿!
查看>>
Redis字符串类型内部编码剖析
查看>>
TensorFlow实战(一)-人工智能基础知识
查看>>
ubuntu16下安装metasploit的笔记
查看>>
JavaScript MVC 学习笔记(三)类的使用(中)
查看>>
Hibernate-ORM:04.Hibernate中的get()和load()
查看>>
邮件推送的邮件模板如何编辑退订代码?
查看>>
交换机芯片探秘
查看>>
微信小程序navigator的open-type跳转问题
查看>>
Hibernate【与Spring整合】
查看>>