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>& nums) {
    int l = 0;
    int r = nums.size() - 1;

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

    return nums;
  }
};
 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[] nums) {
    int l = 0;
    int r = nums.length - 1;

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

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

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

    return nums