Algorithm


Problem Name: 905. Sort Array By Parity

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

 

Example 1:

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Example 2:

Input: nums = [0]
Output: [0]

 

Constraints:

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000
 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int[] sortArrayByParity(int[] A) {
    int evenIdx = 0;
    int oddIdx = A.length - 1;
    while (evenIdx  <  oddIdx) {
      if (A[evenIdx] % 2 == 0) {
        evenIdx++;
      } 
      else {
        int temp = A[evenIdx];
        A[evenIdx] = A[oddIdx];
        A[oddIdx--] = temp;
      }
    }
    return A;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [3,1,2,4]

Output

x
+
cmd
[2,4,3,1]

#2 Code Example with Javascript Programming

Code - Javascript Programming


const sortArrayByParity = function(A) {
    for(let i = 0, len = A.length; i  <  len;) {
      if(A[i] % 2 !== 0) {
        A.push(A[i])
        A.splice(i, 1)
        len--
      } else {
        i++
      }
    }
    return A
}; 
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [3,1,2,4]

Output

x
+
cmd
[2,4,3,1]

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def sortArrayByParity(self, A):
        return [a for a in A if not a % 2] + [a for a in A if a % 2]
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0]

Output

x
+
cmd
[0]

#4 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0905_SortArrayByParity
    {
        public int[] SortArrayByParity(int[] A)
        {
            int left = 0;
            int right = A.Length - 1;
            while (left  <  right)
            {
                while (left < right && A[left] % 2 == 0) left++;
                while (left < right && A[right] % 2 == 1) right--;

                var temp = A[left];
                A[left] = A[right];
                A[right] = temp;
            }

            return A;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [0]

Output

x
+
cmd
[0]
Advertisements

Demonstration


Previous
#904 Leetcode Fruit Into Baskets Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#906 Leetcode Super Palindromes Solution in C, C++, Java, JavaScript, Python, C# Leetcode