Skip to content

Commit 9a05906

Browse files
realDuYuanChaogithub-actions
andauthored
Leetcode 2021.3.16 (examplehub#75)
* sort-array-by-parity * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 3e16136 commit 9a05906

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/** https://leetcode.com/problems/sort-array-by-parity/ */
7+
public class SortArrayByParity {
8+
public static int[] solution1(int[] nums) {
9+
List<Integer> evenNums = new ArrayList<>();
10+
List<Integer> oddNums = new ArrayList<>();
11+
for (int num : nums) {
12+
if (num % 2 == 0) {
13+
evenNums.add(num);
14+
} else {
15+
oddNums.add(num);
16+
}
17+
}
18+
evenNums.addAll(oddNums);
19+
return evenNums.stream().mapToInt(i -> i).toArray();
20+
}
21+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.examplehub.leetcode.easy;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import java.util.Arrays;
6+
import org.junit.jupiter.api.Test;
7+
8+
class SortArrayByParityTest {
9+
@Test
10+
void testSolution1() {
11+
int[] nums = {3, 1, 2, 4};
12+
assertEquals(
13+
Arrays.toString(SortArrayByParity.solution1(nums)),
14+
Arrays.toString(new int[] {2, 4, 3, 1}));
15+
}
16+
}

0 commit comments

Comments
 (0)