LeetCode Solutions

905. Sort Array By Parity

Time:

Space:

			

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

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

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