Sort Array By Parity
LeetCode https://leetcode.cn/problems/sort-array-by-parity/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] sortArrayByParity(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int left = 0, right = n - 1;
for (int num : nums) {
if (num % 2 == 0) {
res[left++] = num;
} else {
res[right--] = num;
}
}
return res;
}
}
Complexity
- Time = O(n)
- Space = O(1)
This post is licensed under CC BY 4.0 by the author.