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 <= A.length <= 5000
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 makesj-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.