2149. Rearrange Array Elements by Sign

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> rearrangeArray(vector<int>& nums) {
int l = 0, r = 1, n= nums.size();
vector<int> ret(n,0);
for(int i=0;i<n;++i){
if(nums[i]>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)