[InterviewBit] Rearrange Array

Rearrange Array

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void Solution::arrange(vector<int> &A) {
for(int i = 0; i < A.size(); i++) {
if(A[i] < 0) continue;
if(A[A[i]] == A[i]) continue;
int origin = A[A[i]], now = A[i];
while(now >= 0 and A[origin] >= 0) {
swap(A[origin], A[now]);
int pos = origin;
origin = A[now];
if(A[now] == 0) A[now] = INT_MIN;
else if(A[now] > 0) A[now] = -A[now];
now = pos;
}
if(A[i] == 0) A[i] = INT_MIN;
else if(A[i] > 0) A[i] = -A[i];
}

for(int i = 0; i < A.size(); i++) {
if(A[i] == INT_MIN) A[i] = 0;
else if(A[i] < 0) A[i] = -A[i];
}
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/05/PS/interviewbit/rearrange-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.