-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode905.java
More file actions
34 lines (31 loc) · 1.01 KB
/
LeetCode905.java
File metadata and controls
34 lines (31 loc) · 1.01 KB
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
33
34
import java.util.Arrays;
public class LeetCode905 {
public static void main(String[] args) {
// 输入:nums = [3,1,2,4]
// 输出:[2,4,3,1]
// 解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
System.out.println(Arrays.toString(new Solution905().sortArrayByParity(new int[] { 3, 1, 2, 4 })));
// 输入:nums = [0]
// 输出:[0]
System.out.println(Arrays.toString(new Solution905().sortArrayByParity(new int[] { 0 })));
}
}
class Solution905 {
public int[] sortArrayByParity(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
while (left < right && nums[left] % 2 == 0) {
left++;
}
while (left < right && nums[right] % 2 == 1) {
right--;
}
int temp;
temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
return nums;
}
}