1.题目要求:
给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
返回满足此条件的 任一数组 作为答案。
示例 1:
输入:nums = [3,1,2,4]
输出:[2,4,3,1]
解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
示例 2:
输入:nums = [0]
输出:[0]
2.题目代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArrayByParity(int* nums, int numsSize, int* returnSize) {
int* number = (int*)malloc(sizeof(int) * numsSize);
int count1 = 0;
int i = 0;
for(i = 0;i < numsSize;i++)
{
if(nums[i] % 2 == 0){
count1++;
}
}
int count2 = 0;
for(i = 0;i < numsSize;i++)
{
if(nums[i] % 2 != 0)
{
count2++;
}
}
int* number1 = (int*)malloc(sizeof(int) * count1);
int* number2 = (int*)malloc(sizeof(int) * count2);
int j_1 = 0;
int j_2 = 0;
for(i = 0;i < numsSize;i++){
if(nums[i] % 2 == 0){
number1[j_1] = nums[i];
j_1++;
}else{
number2[j_2] = nums[i];
j_2++;
}
}
int j = 0;
i = 0;
while(j < j_1){
number[i] = number1[j];
j++;
i++;
}
j = 0;
while(j < j_2){
number[i] = number2[j];
j++;
i++;
}
*returnSize = numsSize;
return number;
}