leetcode刷題記錄 easy(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

中文題目解釋:

給定一個A非負整數數組,返回一個由所有偶數元素組成的數組A,後跟所有奇數元素A

您可以返回滿足此條件的任何答案數組。

例1:

輸入:[3,1,2,4]

輸出:[2,4,3,1] 產出[4,2,3,1],[2,4,1,3]和[4,2,1,3]也將被接受。

注意:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

解析:

遍歷數組A,滿足偶數的值正序放入新數組,滿足奇數的值倒序放入新數組即可

提交結果:

 

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int[] B=new int[A.length];
        int start=0;
        for(int i=0;i<A.length;i++){
            if(A[i]%2==0){
                B[i-start]=A[i];
            }else{
                B[A.length-start-1]=A[i];
                start++;
            }
        }
        return B;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章