LeetCode-in-Java

3467. Transform Array by Parity

Easy

You are given an integer array nums. Transform nums by performing the following operations in the exact order specified:

  1. Replace each even number with 0.
  2. Replace each odd numbers with 1.
  3. Sort the modified array in non-decreasing order.

Return the resulting array after performing these operations.

Example 1:

Input: nums = [4,3,2,1]

Output: [0,0,1,1]

Explanation:

Example 2:

Input: nums = [1,5,1,4,2]

Output: [0,0,1,1,1]

Explanation:

Constraints:

Solution

public class Solution {
    public int[] transformArray(int[] nums) {
        int size = nums.length;
        int[] ans = new int[size];
        int countEven = 0;
        for (int num : nums) {
            if ((num & 1) == 0) {
                countEven++;
            }
        }
        for (int i = countEven; i < size; i++) {
            ans[i] = 1;
        }
        return ans;
    }
}