922. 按奇偶排序数组 II

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {

    private void swap(int[] nums, int a, int b) {
        int t = nums[a];
        nums[a] = nums[b];
        nums[b] = t;
    }

    public int[] sortArrayByParityII(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }

        int evenIndex = nums.length, oddIndex = nums.length + 1;
        int index = 0;

        while (index < evenIndex && index < oddIndex) {
            if (nums[index] % 2 == index % 2) {
                index++;
            } else {
                if (nums[index] % 2 == 1) {
                    oddIndex -= 2;
                    swap(nums, index, oddIndex);
                } else {
                    evenIndex -= 2;
                    swap(nums, index, evenIndex);
                }
            }
        }

        return nums;
    }
}
posted @ 2021-12-16 16:05  Tianyiya  阅读(45)  评论(0)    收藏  举报