LeetCode Solutions

922. Sort Array By Parity II

Time:

Space:

			

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;
  }
};
			

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;
  }
}
			

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