← Static tasks

922. Sort Array By Parity II

leetcode medium

#array#csharp#leetcode#medium#sort#two-pointers

Task

Дан массив целых чисел nums, половина целых чисел в нем нечетные, а другая половина - четные. Отсортируйте массив так, чтобы во всех случаях, когда nums[i] нечетный, i был нечетным, а во всех случаях, когда nums[i] четный, i был четным. Верните любой массив ответов, удовлетворяющий этому условию.

Пример:

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

Output: [4,5,2,7]

C# solution

matched/original
public class Solution {
    public int[] SortArrayByParityII(int[] nums) {
        int[] result = new int[nums.Length];
        int evenIdx = 0;
        int oddIdx = 1;
        
        foreach (int num in nums) {
            if (num % 2 == 0) {
                result[evenIdx] = num;
                evenIdx += 2;
            } else {
                result[oddIdx] = num;
                oddIdx += 2;
            }
        }
        
        return result;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& SortArrayByParityII(vector<int>& nums) {
        vector<int>& result = new int[nums.size()];
        int evenIdx = 0;
        int oddIdx = 1;
        
        foreach (int num in nums) {
            if (num % 2 == 0) {
                result[evenIdx] = num;
                evenIdx += 2;
            } else {
                result[oddIdx] = num;
                oddIdx += 2;
            }
        }
        
        return result;
    }
}

Java solution

matched/original
class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        int[] result = new int[nums.length];
        int evenIdx = 0;
        int oddIdx = 1;
        
        for (int num : nums) {
            if (num % 2 == 0) {
                result[evenIdx] = num;
                evenIdx += 2;
            } else {
                result[oddIdx] = num;
                oddIdx += 2;
            }
        }
        
        return result;
    }
}

JavaScript solution

matched/original
var sortArrayByParityII = function(nums) {
    const result = new Array(nums.length);
    let evenIdx = 0;
    let oddIdx = 1;
    
    for (const num of nums) {
        if (num % 2 === 0) {
            result[evenIdx] = num;
            evenIdx += 2;
        } else {
            result[oddIdx] = num;
            oddIdx += 2;
        }
    }
    
    return result;
};

Python solution

matched/original
def sortArrayByParityII(nums):
    result = [0] * len(nums)
    even_idx, odd_idx = 0, 1
    for num in nums:
        if num % 2 == 0:
            result[even_idx] = num
            even_idx += 2
        else:
            result[odd_idx] = num
            odd_idx += 2
    return result

Explanation

Algorithm

Инициализировать два указателя even_idx и odd_idx для отслеживания позиций четных и нечетных индексов соответственно.

Пройти по массиву nums и для каждого элемента:

Если элемент четный, поместить его на позицию even_idx и увеличить even_idx на 2.

Если элемент нечетный, поместить его на позицию odd_idx и увеличить odd_idx на 2.

Вернуть отсортированный массив.

😎