922. Sort Array By Parity II

problem

solution

option 1 - one pass

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
int n = nums.size() , l = 0, r = 1;
vector<int> ret(n,0);
for(int i = 0;i<n;++i){
if(nums[i]%2==0){
ret[l] = nums[i];
l+=2;
}
else{
ret[r] = nums[i];
r+=2;
}
}
return ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)