力扣922

LeetCode算法题 922. 按奇偶排序数组 II

题目描述: 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当A[i] 为偶数时, i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

方法1:二次遍历
思路:第一次遍历把所有的偶数放在索引为偶数的位置上,第二次遍历就放奇数。

 public static int[] sortArrayByParityII(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int i = 0;
        //把偶数放在 索引为偶数的位置上
        for (int num : nums) {
            if ((num & 1) == 0) {
                ans[i] = num;
                i += 2;
            }
        }
        i = 1;
        //把奇数放在 索引为奇数的位置上
        for (int num : nums) {
            if ((num & 1) != 0) {
                ans[i] = num;
                i += 2;
            }
        }
        return ans;
    }

方法2:一次遍历
思路:定义o,j两个指针分别指向偶数索引、奇数索引,一次遍历分别把偶数、奇数放在对应的索引位置上。

public static int[] sortArrayByParityII(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int o = 0, j = 1;
        for (int i = 0; i < len; i++) {
            if ((nums[i] & 1) == 0) {
                //偶数
                ans[o] = nums[i];
                o += 2;
            } else {
                //奇数
                ans[j] = nums[i];
                j += 2;
            }
        }
        return ans;
    }

方法3:双指针遍历
思路:定义o,j两个指针分别指向偶数索引、奇数索引。遍历时定义2个指针,一个从前往后遍历,一个从后往前遍历,遍历时间复杂度O(n/2)。

public static int[] sortArrayByParityII(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int o = 0, j = 1;
        for (int low = 0, high = len - 1; low <= high; low++, high--) {
            //从前往后找
            if ((nums[low] & 1) == 0) {
                ans[o] = nums[low];
                o += 2;
            } else {
                ans[j] = nums[low];
                j += 2;
            }

            //从后往前找
            if ((nums[high] & 1) == 0) {
                ans[o] = nums[high];
                o += 2;
            } else {
                ans[j] = nums[high];
                j += 2;
            }
        }
        return ans;
    }

题解链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii/solution/er-ci-bian-li-yi-ci-bian-li-shuang-zhi-z-7ew4/

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值