Skip to content

905. Sort Array By Parity 👍

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

    while (l < r) {
      if (A[l] % 2 == 1 && A[r] % 2 == 0)
        swap(A[l], A[r]);
      if (A[l] % 2 == 0)
        ++l;
      if (A[r] % 2 == 1)
        --r;
    }

    return A;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int[] sortArrayByParity(int[] A) {
    int l = 0;
    int r = A.length - 1;

    while (l < r) {
      if (A[l] % 2 == 1 && A[r] % 2 == 0) {
        int temp = A[l];
        A[l] = A[r];
        A[r] = temp;
      }
      if (A[l] % 2 == 0)
        ++l;
      if (A[r] % 2 == 1)
        --r;
    }

    return A;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def sortArrayByParity(self, A: List[int]) -> List[int]:
    l = 0
    r = len(A) - 1

    while l < r:
      if A[l] % 2 == 1 and A[r] % 2 == 0:
        A[l], A[r] = A[r], A[l]
      if A[l] % 2 == 0:
        l += 1
      if A[r] % 2 == 1:
        r -= 1

    return A