LeetCode刷题 - #905. 按奇偶排序数组

116 阅读1分钟

905. 按奇偶排序数组

给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。 返回满足此条件的 任一数组 作为答案。

示例 1:

输入:nums = [3,1,2,4]
输出:[2,4,3,1]
解释:[4,2,3,1][2,4,1,3][4,2,1,3] 也会被视作正确答案。

示例 2:

输入:nums = [0]
输出:[0]

答题思路

需要解决的问题:

  • 什么是奇数/偶数
num % 2 == 0 偶数
num % 2 == 1 奇数
  • 方向: 只遍历一遍

可确定,数组头部是偶数,尾部是奇数

①使用双指针 start = 0; end = length - 1;

start指向偶数就往后遍历,end指向奇数就往前遍历

③当start指向奇数,end指向偶数,二者就交换

最终代码

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int start = 0;
        int end = nums.length - 1;
        while(start < end) {
            while(start < end && nums[start] % 2 == 0) {
                start ++;
            }
            while(start < end && nums[end] % 2 == 1) {
                end --;
            }
            if(start < end) {
                swap(nums, start, end);
            }
        }
        return nums;
    }
    private void swap(int[] nums, int first, int second) {
        int temp = nums[first];
        nums[first] = nums[second];
        nums[second] = temp;
    }
}