-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortArrayByParity.java
More file actions
32 lines (27 loc) · 936 Bytes
/
SortArrayByParity.java
File metadata and controls
32 lines (27 loc) · 936 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package solutions;
import java.util.Arrays;
// [Problem] https://leetcode.com/problems/sort-array-by-parity
class SortArrayByParity {
// Two pointers
// O(n) time, O(n) space
public int[] sortArrayByParity(int[] nums) {
int[] sortedNums = new int[nums.length];
int evenIndex = 0, oddIndex = nums.length - 1;
for (int num : nums) {
if (num % 2 == 0) {
sortedNums[evenIndex++] = num;
} else {
sortedNums[oddIndex--] = num;
}
}
return sortedNums;
}
// test
public static void main(String[] args) {
SortArrayByParity solution = new SortArrayByParity();
int[] nums = {3, 1, 2, 4};
int[] expectedOutput = {2, 4, 1, 3};
int[] actualOutput = solution.sortArrayByParity(nums);
System.out.println("Test passed? " + Arrays.equals(expectedOutput, actualOutput));
}
}