LeetCode - 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 <= 5000
0 <= A[i] <= 5000
水题
class Solution { public int[] sortArrayByParity(int[] A) { if (A == null) return null; int[] ret = new int[A.length]; int k = A.length-1, j=0; for (int i=0; i<A.length; i++) { if (isEven(A[i])) { ret[j++] = A[i]; } else { ret[k--] = A[i]; } } return ret; } private boolean isEven(int n) { return (n & 1) == 0; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。