Skip to content

Commit a8f1ee2

Browse files
authored
Create 0905. Sort Array By Parity
1 parent a72b658 commit a8f1ee2

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

0905. Sort Array By Parity

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/****************************************
2+
905. Sort Array By Parity
3+
4+
Difficulty: Easy
5+
6+
Given an array A of non-negative integers,
7+
return an array consisting of all the even elements of A,
8+
followed by all the odd elements of A.
9+
You may return any answer array that satisfies this condition.
10+
11+
Example 1:
12+
Input: [3,1,2,4]
13+
Output: [2,4,3,1]
14+
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
15+
16+
Note:
17+
1 <= A.length <= 5000
18+
0 <= A[i] <= 5000
19+
****************************************/
20+
21+
22+
class Solution {
23+
public int[] sortArrayByParity(int[] A) {
24+
int i = 0, j = A.length - 1;
25+
26+
while (i < j) {
27+
if (A[i] % 2 == 1 && A[j] % 2 == 0) {
28+
int tmp = A[i];
29+
A[i] = A[j];
30+
A[j] = tmp;
31+
}
32+
33+
if (A[i] % 2 == 0) {
34+
i++;
35+
}
36+
if (A[j] % 2 == 1) {
37+
j--;
38+
}
39+
}
40+
41+
return A;
42+
}
43+
}
44+

0 commit comments

Comments
 (0)