zoukankan      html  css  js  c++  java
  • 922. 按奇偶排序数组 II

    给定一个非负整数数组 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] 也会被接受。
    

    提示:

    1. 2 <= A.length <= 20000
    2. A.length % 2 == 0
    3. 0 <= A[i] <= 1000

    解法:创建两个数组,遍历一遍数组,一个存放奇数,一个存放偶数,再遍历一遍数组,将奇偶放入指定位置即可

    class Solution {
        public int[] sortArrayByParityII(int[] A) {
            
            int[] oldNum = new int[A.length/2];
            int[] evenNum = new int[A.length/2];
            int p1 = 0,p2 = 0;
            for(int i=0;i<A.length;i++){
                if(A[i] % 2 == 0){
                    evenNum[p2++] = A[i];
                }else{
                    oldNum[p1++] = A[i];
                }
            }
            p1 = 0;
            p2 = 0;
            for(int i=0;i<A.length;i++){
                if(i % 2 == 0){
                    A[i] = evenNum[p2++];
                }else{
                    A[i] = oldNum[p1++];
                }
            }
            return A;
        }
    }
  • 相关阅读:
    Add two numbers
    House Robber && House Robber II
    Clone Graph
    224. Basic Calculator
    29. Divide Two Integers
    365. Water and Jug Problem
    435. Non-overlapping Intervals
    452. Minimum Number of Arrows to Burst Balloons
    138. Copy List with Random Pointer
    43. Multiply Strings
  • 原文地址:https://www.cnblogs.com/czsy/p/10961233.html
Copyright © 2011-2022 走看看