https://leetcode.com/problems/rearrange-array-elements-by-sign/
- Two Pointer
- In-place
Use two pointers to place positive and negative elements alternately or collect and rebuild.
O(n)
O(1) or O(n) depending on method
class Solution {
public int[] rearrangeArray(int[] nums) {
int[] res = new int[nums.length];
int pos = 0, neg = 1;
for (int n : nums) {
if (n > 0) { res[pos] = n; pos += 2; }
else { res[neg] = n; neg += 2; }
}
return res;
}
}