[LeetCode] Rearrange Array Elements by Sign

2149. Rearrange Array Elements by Sign

You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

You should rearrange the elements of nums such that the modified array follows the given conditions:

  1. Every consecutive pair of integers have opposite signs.
  2. For all integers with the same sign, the order in which they were present in nums is preserved.
  3. The rearranged array begins with a positive integer.

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

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>& A) {
vector<int> neg, pos;
int n = A.size();
for(auto& a : A) {
if(a < 0) neg.push_back(a);
else pos.push_back(a);
}
for(int i = 0, j = 0; i < n; i += 2, j++) {
A[i] = pos[j];
}
for(int i = 1, j = 0; i < n; i += 2, j++) {
A[i] = neg[j];
}
return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/29/PS/LeetCode/rearrange-array-elements-by-sign/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.