Leetcode 905. Sort Array By Parity, Java解法

博客介绍了对非负整数数组进行排序,使偶数在前奇数在后的两种方法。方法一是借鉴快速排序思想的单循环双指针法,时间复杂度O(N),空间复杂度O(1);方法二是先放偶数再放奇数的两次遍历法,时间复杂度O(N),空间复杂度O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

Approach #1 我的解法,one loop, double pointer 

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int len = A.length;
        int j = 0;
        int k = len-1;
        while(j<k){
            if(A[j]%2==0){
                j+=1; 
            } 
            else{
                int temp = A[k];
                A[k] = A[j];
                A[j] = temp;
                k-=1;
            }
        }
        return A;
    }
}

这个方法其实借鉴了快速排序算法的思想。

Complexity Analysis

  • Time Complexity: O(N), where N is the length of A. Each step of the while loop makes j-i decrease by at least one. (Note that while quicksort is O(Nlog N)normally, this is O(N)O(N) because we only need one pass to sort the elements.)

  • Space Complexity: O(1) in additional space complexity. 

Approach #2 Two Pass

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int[] ans = new int[A.length];
        int t = 0;

        for (int i = 0; i < A.length; ++i)
            if (A[i] % 2 == 0)
                ans[t++] = A[i];

        for (int i = 0; i < A.length; ++i)
            if (A[i] % 2 == 1)
                ans[t++] = A[i];

        return ans;
    }
}

先把所有even number放进去,再把所有odd number 放进去。

Complexity Analysis

  • Time Complexity: O(N)O(N), where NN is the length of A.

  • Space Complexity: O(N)O(N), the space used by the answer. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值