Untitled
unknown
plain_text
9 months ago
990 B
4
Indexable
public class RearrangeArrayBySign {
public static int[] rearrangeArray(int[] nums) {
int n = nums.length;
int[] result = new int[n];
// Pointers for positive and negative placement
int posIndex = 0; // Next position for a positive number
int negIndex = 1; // Next position for a negative number
// Traverse the array
for (int num : nums) {
if (num > 0) {
result[posIndex] = num;
posIndex += 2; // Move to the next positive position
} else {
result[negIndex] = num;
negIndex += 2; // Move to the next negative position
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {3, 1, -2, -5, 2, -4};
int[] result = rearrangeArray(nums);
System.out.println(java.util.Arrays.toString(result)); // Output: [3, -2, 1, -5, 2, -4]
}
}
Editor is loading...
Leave a Comment