Skip to content

[LeetCode] 922. 按奇偶排序数组 II #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Jul 31, 2019 · 0 comments
Open

[LeetCode] 922. 按奇偶排序数组 II #17

Animenzzzz opened this issue Jul 31, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个非负整数数组 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

解题思路:没有想太多。直接一次遍历先存下奇数和偶数数组,再遍历一次把值赋上

C解题:

int* sortArrayByParityII(int* A, int ASize, int* returnSize){
    int ji[ASize/2],ou[ASize/2];
    int ji_index = 0,ou_index = 0;
    int *result = (int *)malloc(ASize*sizeof(int));
    *returnSize = 0;
    for (int i = 0; i < ASize; i++)
    {
        if (A[i]%2 == 0) ou[ou_index++] = A[i];
        else ji[ji_index++] = A[i];
    }
    ji_index = 0;ou_index = 0;
    for (int i = 0; i < ASize; i++)
    {
        if (i%2 == 0) result[*returnSize] = ou[ou_index++];
        else result[*returnSize] = ji[ji_index++];
        (*returnSize)++;
    }
    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant