All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 10, 2024
Last updated : July 01, 2024
Related Topics : Array, Two Pointers, Simulation
Acceptance Rate : 84.11 %
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* rearrangeArray(int* nums, int numsSize, int* returnSize) {
int* output = (int*) malloc(sizeof(int) * numsSize);
int outputCurrent = 0;
*returnSize = numsSize;
int neg = 0;
int pos = 0;
while (outputCurrent < numsSize) {
while (nums[neg] > 0) {
neg++;
}
while (nums[pos] < 0) {
pos++;
}
output[outputCurrent] = nums[pos];
output[outputCurrent + 1] = nums[neg];
outputCurrent += 2;
neg++;
pos++;
}
return output;
}
class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
output = [0] * len(nums)
outputIndex = 0
pos, neg = 0, 0
while outputIndex < len(nums) :
while nums[pos] < 0 :
pos += 1
while nums[neg] > 0 :
neg += 1
output[outputIndex] = nums[pos]
output[outputIndex + 1] = nums[neg]
outputIndex += 2
pos += 1
neg += 1
return output