LeetCode每日一题: 按奇偶排序数组 II(No.27)

栏目: 编程工具 · 发布时间: 6年前

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
复制代码

示例:

输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
复制代码

思考:

用两个list,分辨存放奇数和偶数,循环遍历将数组元素放入,再次循环根据下标奇偶将元素放入。
复制代码

实现:

class Solution {
    public int[] sortArrayByParityII(int[] A) {
        int length = A.length;
        ArrayList<Integer> nums1 = new ArrayList<>();
        ArrayList<Integer> nums2 = new ArrayList<>();
        for (int count = 0; count < length; count++) {
            if (A[count] % 2 != 0) {
                nums1.add(A[count]);
            } else if (A[count] % 2 != 1) {
                nums2.add(A[count]);
            }
        }
        for (int count = 0; count < length; count++) {
            if (count % 2 == 0) {
                A[count] = nums2.remove(0);
            } else if (count % 2 == 1) {
                A[count] = nums1.remove(0);
            }
        }
        return A;
    }

}复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95

Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换