给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp(const void *_a, const void *_b) {
int *a = *(int *)_a, *b = *(int *)_b;
return a - b;
}
int* sortArrayByParityII(int* A, int ASize, int* returnSize){
qsort(A, ASize, sizeof(int), cmp);
int *res = malloc(sizeof(int) * ASize);
*returnSize = ASize;
int step = 0;
for (int i = 0; i < ASize; i++) {
if (A[i] % 2 == 0) {
res[step] = A[i];
step += 2;
}
}
step = 1;
for (int i = 0; i < ASize; i++) {
if (A[i] % 2 == 1) {
res[step] = A[i];
step += 2;
}
}
return res;
}
func sortArrayByParityII(A []int) []int {
res := make([]int, len(A))
step := 0
for _, v := range A {
if v % 2 == 0 {
res[step] = v
step += 2
}
}
step = 1
for _, v := range A {
if v % 2 == 1 {
res[step] = v
step += 2
}
}
return res
}
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& A) {
int n = A.size();
int j = 1;
for (int i = 0; i < n; i += 2) {
if (A[i] % 2 == 1) {
while (A[j] % 2 == 1) {
j += 2;
}
swap(A[i], A[j]);
}
}
return A;
}
};