layout: posttitle: PHP 实现按奇偶排序数组
subtitle: PHP 实现按奇偶排序数组
date: 2020-04-28
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 奇偶排序数组

题干

给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。

你可以返回满足此条件的任何数组作为答案。

示例:

  1. 输入:[3,1,2,4]
  2. 输出:[2,4,3,1]
  3. 输出 [4,2,3,1],[2,4,1,3] [4,2,1,3] 也会被接受。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity

其实就是顺序遍历,相邻两个元素进行比较,奇偶则互换位置,非奇偶保持不动。

PHP 实现

function sortArrayByParity($nums)
{
    $count = count($nums);
    if ($count <= 0) {
        return 0;
    }

    $i = -1;
    for ($j = 0; $j < $count; $j++) {
        if ($nums[$j] % 2 !== 0) {
            $i++;
            list($nums[$i], $nums[$j]) = [$nums[$j], $nums[$i]];
        }
    }
    return $nums;
}

return sortArrayByParity([6,3,2,1,4]); // output: [3,1,2,6,4]

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券