905. 按奇偶排序数组『简单』

题目来源于力扣(LeetCode

一、题目

905. 按奇偶排序数组

题目相关标签:数组

提示:

  • 1 <= A.length <= 5000
  • 0 <= A[i] <= 5000

二、解题思路

  1. 定义左右指针,遍历数组

  2. 左指针右移查找奇数元素,查找到时,右指针左移查找偶数元素,当左右指针上的元素分别为奇数与偶数时,完成一次交换

三、代码实现

public static int[] sortArrayByParity(int[] A) {
    int[] nums = A;
    int left = 0;
    int right = nums.length - 1;

    while (left < right) {
        if ((nums[left] & 1) == 1) {
            if ((nums[right] & 1) == 0) {
                // 左侧为奇数,右侧为偶数时交换
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
            }
            // 右侧为奇数或偶数时,都向左侧移动
            right--;
        } else {
            // 左侧为偶数时跳过
            left++;
        }
    }
    return nums;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    int[] nums = {3, 1, 2, 4};  // output: {2, 4, 3, 1}

    int[] result = sortArrayByParity(nums);
    System.out.println(Arrays.toString(result));
}
posted @ 2020-07-01 21:08  知音12138  阅读(150)  评论(0编辑  收藏  举报