描述
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
思路
我们可以借鉴一下快排的思想,设两个指针i,j分别指向数组头,数组尾,然后检查i指向的如果是偶数,i++,j如果指向的是奇数,j--,如果遇到了i指向奇数,j指向偶数,则两个交换一下。看了一下讨论区的代码,大体都是这么做的。
代码
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int i = 0;
int j = A.size()-1;
int tmp;
while(i<j)//停止条件
{
while(A[i]%2==0)//找到i指向的奇数
i++;
while(A[j]%2==1)//找到j指向的偶数
j--;
if(i<j)//如果没有发生越界,i,j交换一下
{
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
i++;
j--;
}
}
return A;
}
};
网友评论