Skip to content
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

✅922. 按奇偶排序数组 II #58

Open
bazinga-web opened this issue Jul 13, 2020 · 2 comments
Open

✅922. 按奇偶排序数组 II #58

bazinga-web opened this issue Jul 13, 2020 · 2 comments

Comments

@bazinga-web
Copy link

922. 按奇偶排序数组II

给定一个非负整数数组 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] 也会被接受。

提示:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000
@bazinga-web
Copy link
Author

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortArrayByParityII = function (A) {
    let j = 1;
    for (let i = 0; i < A.length; i += 2) {
        if (A[i] % 2 === 1) {
            while (A[j] % 2 === 1) {
                j += 2;
            }
            [A[i], A[j]] = [A[j], A[i]];
        }
    }
    return A;
};

@Ray-56
Copy link
Owner

Ray-56 commented Jul 14, 2020

/**
 * @param {number[]} A
 * @return {number[]}
 */
var sortArrayByParityII = function(A) {
    let j = 1; // j 为奇数下标保证值也是奇数
    for (let i = 0; i < A.length; i += 2) { // i 为偶数下标保证值也是偶数
        if (A[i] % 2 === 1) {
            while (A[j] % 2 === 1) { // 不用处理越界,取不到为 undefined,再取模为 NaN,不会等于 1
                j += 2;
            }
            const temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
    }
    return A;
};

@Ray-56 Ray-56 changed the title 922. 按奇偶排序数组 II ✅922. 按奇偶排序数组 II Jul 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants