我是靠谱客的博主 真实钢笔,这篇文章主要介绍leetcode-905-数组排序,现在分享给大家,希望可以做个参考。

法一:对数组进行排序,将所有的偶数放到奇数的前面,我们可以考虑使用两个for循环,先将所有的偶数存到数组中,在将所有的奇数存进去

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution { public int[] sortArrayByParity(int[] A) { int[] B = new int[A.length]; int t = 0; for(int i = 0;i<A.length;i++){ if(A[i]%2 == 0) B[t++] = A[i]; } for(int i = 0;i<A.length;i++){ if(A[i]%2 != 0) B[t++] = A[i]; } return B; } }

法二:通过比较器对数组进行排序

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution { public int[] sortArrayByParity(int[] A) { Integer[] B = new Integer[A.length]; for (int t = 0; t < A.length; ++t) B[t] = A[t]; Arrays.sort(B, (a, b) -> Integer.compare(a%2, b%2)); for (int t = 0; t < A.length; ++t) A[t] = B[t]; return A; /* Alternative: return Arrays.stream(A) .boxed() .sorted((a, b) -> Integer.compare(a%2, b%2)) .mapToInt(i -> i) .toArray(); */ } }

 

最后

以上就是真实钢笔最近收集整理的关于leetcode-905-数组排序的全部内容,更多相关leetcode-905-数组排序内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部