LeetCode - Algorithms - 905. Sort Array By Parity

It’s easy indeed.

Problem

905. Sort Array By Parity

Java

Two Pass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] sortArrayByParity(int[] A) {
final int N = A.length;
int[] B = new int[N];
int left=0, right=N-1;
for(int i=0; i<N; i++) {
if ((A[i]&1)==0) {
B[left++]=A[i];
}
else {
B[right--]=A[i];
}
}
return B;
}
}

Submission Detail

  • 285 / 285 test cases passed.
  • Runtime: 1 ms, faster than 99.47% of Java online submissions for Sort Array By Parity.
  • Memory Usage: 40.1 MB, less than 30.13% of Java online submissions for Sort Array By Parity.

In-Place

© Solution - Approach 3: In-Place

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] sortArrayByParity(int[] A) {
final int N = A.length;
int left = 0, right = N - 1;
int temp;
while (left < right) {
if ((A[left] & 1)==1 && (A[right] & 1)==0) {
temp = A[left];
A[left] = A[right];
A[right] = temp;
}
if ((A[left] & 1) == 0) left++;
if ((A[right] & 1) == 1) right--;
}
return A;
}
}

Submission Detail

  • 285 / 285 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Sort Array By Parity.
  • Memory Usage: 39.6 MB, less than 30.13% of Java online submissions for Sort Array By Parity.