Skip to content

922. Sort Array By Parity II 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<int> sortArrayByParityII(vector<int>& A) {
    const int n = A.size();

    for (int i = 0, j = 1; i < n; i += 2, j += 2) {
      while (i < n && A[i] % 2 == 0)
        i += 2;
      while (j < n && A[j] % 2 == 1)
        j += 2;
      if (i < n)
        swap(A[i], A[j]);
    }

    return A;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int[] sortArrayByParityII(int[] A) {
    final int n = A.length;

    for (int i = 0, j = 1; i < n; i += 2, j += 2) {
      while (i < n && A[i] % 2 == 0)
        i += 2;
      while (j < n && A[j] % 2 == 1)
        j += 2;
      if (i < n) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
      }
    }

    return A;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def sortArrayByParityII(self, A: List[int]) -> List[int]:
    n = len(A)

    i = 0
    j = 1
    while i < n:
      while i < n and A[i] % 2 == 0:
        i += 2
      while j < n and A[j] % 2 == 1:
        j += 2
      if i < n:
        A[i], A[j] = A[j], A[i]
      i += 2
      j += 2

    return A