给定一个非负整数数组 A
,返回一个由 A
的所有偶数元素组成的数组,后面跟 A
的所有奇数元素。
你可以返回满足此条件的任何数组作为答案。
示例:
输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
提示:
1 <= A.length <= 5000
0 <= A[i] <= 5000
C
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArrayByParity(int* A, int ASize, int* returnSize)
{
*returnSize=ASize;
int* temp=(int*)malloc(ASize*sizeof(int));
int n=ASize;
int r=0,k=n-1;
for(int i=0;i<n;i++)
{
if(A[i]%2==0)
{
temp[r]=A[i];
r++;
}
else
{
temp[k]=A[i];
k--;
}
}
return temp;
}
C
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArrayByParity(int* A, int ASize, int* returnSize)
{
int n=ASize;
int left=0;
int right=n-1;
while(left<right)
{
if(A[left]%2==1 && A[right]%2==0)
{
int tmp=A[left];
A[left]=A[right];
A[right]=tmp;
left++;
right--;
}
else
{
if(A[left]%2==0)
{
left++;
}
if(A[right]%2==1)
{
right--;
}
}
}
*returnSize=n;
return A;
}
C++
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A)
{
int n=A.size();
int left=0;
int right=n-1;
while(left<right)
{
if(A[left]%2==1 && A[right]%2==0)
{
swap(A[left],A[right]);
left++;
right--;
}
else
{
if(A[left]%2==0)
{
left++;
}
if(A[right]%2==1)
{
right--;
}
}
}
return A;
}
};
python
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
n=len(A)
left=0
right=n-1
while left<right:
if 1==A[left]%2 and 0==A[right]%2:
A[left],A[right]=A[right],A[left]
left+=1
right-=1
else:
if 0==A[left]%2:
left+=1
if 1==A[right]%2:
right-=1
return A