攻城獅
Not a programmer 不工程的攻城獅

Not a programmer 不工程的攻城獅

LeetCode Solution, Easy, 905. Sort Array By Parity

按奇偶排序陣列

攻城獅's photo
攻城獅
·May 20, 2022·

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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

題目翻譯

這題是有一個整數陣列 nums,要將其中偶數元素往前挪移,奇數往後排序。其中偶數元素間或奇數元素間的排序不要求。

解法解析

這題跟上一篇 Move Zeroes 有 78 成相似,所以可以互相參考一下。但因為不考慮元素間的排序,所以處理方式相對簡單。

解法範例

Go

Sort
func sortArrayByParity(nums []int) []int {
    sort.Slice(nums, func(i, j int) bool {
        return nums[i]%2 < nums[j]%2
    })
    return nums
}
Two Pointers
func sortArrayByParity(nums []int) []int {
    even := []int{}
    odd := []int{}

    for _, v := range nums {
        if v%2 == 0 {
            even = append(even, v)
        } else {
            odd = append(odd, v)
        }
    }

    return append(even, odd...)
}
In Place
func sortArrayByParity(nums []int) []int {
    for i, j := 0, len(nums)-1; i < j; {
        if nums[i]%2 > nums[j]%2 {
            nums[i], nums[j] = nums[j], nums[i]
        }
        if nums[i]%2 == 0 {
            i++
        }
        if nums[j]%2 == 1 {
            j--
        }
    }
    return nums
}

JavaScript

Sort
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParity = function (nums) {
    nums.sort((a, b) => (a % 2) - (b % 2));
    return nums;
};
Two Pointers
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParity = function (nums) {
    const result = new Array();
    nums.forEach((e) => {
        if (e % 2 == 1) {
            result.push(e);
        } else {
            result.unshift(e);
        }
    });

    return result;
};
In Place
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArrayByParity = function (nums) {
    let i = 0,
        j = nums.length - 1;
    while (i < j) {
        if (nums[i] % 2 > nums[j] % 2) {
            [nums[i], nums[j]] = [nums[j], nums[i]];
        }
        if (nums[i] % 2 == 0) {
            i++;
        }
        if (nums[j] % 2 == 1) {
            j--;
        }
    }
    return nums;
};

Kotlin

Sort
class Solution {
    fun sortArrayByParity(nums: IntArray): IntArray {
        return nums.sortedBy { it % 2 }.toIntArray()
    }
}
Two Pointers
class Solution {
    fun sortArrayByParity(nums: IntArray): IntArray {
        return nums.filter { it % 2 == 0 }.toIntArray().plus(nums.filter { it % 2 == 1 })
    }
}
In Place
class Solution {
    fun sortArrayByParity(nums: IntArray): IntArray {
        var i = 0
        var j = nums.size - 1
        while (i < j) {
            if (nums[i] % 2 > nums[j] % 2) {
                nums[i] = nums[j].also { nums[j] = nums[i] }
            }
            if (nums[i] % 2 == 0) {
                i++
            }
            if (nums[j] % 2 == 1) {
                j--
            }
        }
        return nums
    }
}

PHP

Sort
class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer[]
     */
    function sortArrayByParity($nums)
    {
        usort($nums, function ($a, $b) {
            return ($a % 2) - ($b % 2);
        });
        return $nums;
    }
}
Two Pointers
class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer[]
     */
    function sortArrayByParity($nums)
    {
        $even = [];
        foreach ($nums as $num) {
            if ($num % 2 === 0) {
                $even[] = $num;
            }
        }
        return array_merge($even, array_diff($nums, $even));
    }
}
In Place
class Solution
{

    /**
     * @param Integer[] $nums
     * @return Integer[]
     */
    function sortArrayByParity($nums)
    {
        $i = 0;
        $j = count($nums) - 1;
        while ($i < $j) {
            if ($nums[$i] % 2 > $nums[$j] % 2) {
                $tmp = $nums[$i];
                $nums[$i] = $nums[$j];
                $nums[$j] = $tmp;
            }

            if ($nums[$i] % 2 === 0) {
                $i++;
            }
            if ($nums[$j] % 2 === 1) {
                $j--;
            }
        }

        return $nums;
    }
}

Python

Sort
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        nums.sort(key=lambda x: x % 2)
        return nums
Two Pointers
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        return [x for x in nums if x % 2 == 0] + [x for x in nums if x % 2 == 1]
In Place
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        i, j = 0, len(nums) - 1
        while i < j:
            if nums[i] % 2 > nums[j] % 2:
                nums[i], nums[j] = nums[j], nums[i]

            if nums[i] % 2 == 0:
                i += 1
            if nums[j] % 2 == 1:
                j -= 1

        return nums

Rust


Swift

Sort
class Solution {
    func sortArrayByParity(_ nums: [Int]) -> [Int] {
        return nums.sorted {
            $0 % 2 < $1 % 2
        }
    }
}
Two Pointers
class Solution {
    func sortArrayByParity(_ nums: [Int]) -> [Int] {
        return nums.filter { $0 % 2 == 0 } + nums.filter { $0 % 2 == 1 }
    }
}
In Place
class Solution {
    func sortArrayByParity(_ nums: [Int]) -> [Int] {
        var i: Int = 0
        var j: Int = nums.count - 1
        var nums: [Int] = nums
        while i < j {
            if nums[i] % 2 == 0 {
                i += 1
            } else {
                nums.swapAt(i, j)
                j -= 1
            }
        }
        return nums
    }
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this

Impressum

As smiple as possible