LeetCode 每日一题 [53] 调整数组顺序使奇数位于偶数前面

LeetCode 调整数组顺序使奇数位于偶数前面 [简单]

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof

示例:

输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。

提示:

1 <= nums.length <= 50000
1 <= nums[i] <= 10000

题目分析
解法1

从两边进行双指针,同时迭代 如果都是偶数,则右边的 下标-1 ,如果都是奇数,则左边的下标 +1,如果左边是奇数,右边是偶数,则右边下标-1,如果左边是偶数,右边是奇数,则交换,然后左边下标+1,右边下标-1;

解法2

一直进行遍历,直到左边找到偶数,右边找到奇数,然后再进行交换,否则不交换

代码实现
public class ExchangeNumber {
    public static void main(String[] args) {
        int[] target = new int[]{1, 23, 3, 4, 5, 6, 7, 8, 9};
        int[] target2 = new int[]{1, 23, 3, 4, 5, 6, 7, 8, 9};
        System.out.println(Arrays.toString(exchange(target)));
        System.out.println(Arrays.toString(exchange1(target2)));
    }

    public static int[] exchange1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new int[]{};
        }
        int leftIndex = 0;
        int rightIndex = nums.length - 1;
        int temp;
        while (leftIndex < rightIndex) {
            while (leftIndex < rightIndex && (nums[leftIndex] & 1) == 1) {
                leftIndex++;
            }
            while (leftIndex < rightIndex && (nums[rightIndex] & 1) == 0) {
                rightIndex--;
            }
            temp = nums[leftIndex];
            nums[leftIndex] = nums[rightIndex];
            nums[rightIndex] = temp;
        }
        return nums;
    }

    public static int[] exchange(int[] nums) {
        if (nums == null || nums.length == 0) {
            return new int[]{};
        }
        int leftIndex = 0;
        int rightIndex = nums.length - 1;
        while (leftIndex < rightIndex) {
            if ((nums[leftIndex] & 1) != 0 && (nums[rightIndex] & 1) != 0) {
                //奇数 和 奇数
                leftIndex++;
            } else if ((nums[leftIndex] & 1) != 0 && (nums[rightIndex] & 1) == 0) {
                //奇数 和 偶数
                leftIndex++;
                rightIndex--;
            } else if ((nums[leftIndex] & 1) == 0 && (nums[rightIndex] & 1) != 0) {
                // 偶数 和 奇数
                nums[leftIndex] = nums[leftIndex] ^ nums[rightIndex];
                nums[rightIndex] = nums[leftIndex] ^ nums[rightIndex];
                nums[leftIndex] = nums[leftIndex] ^ nums[rightIndex];
                leftIndex++;
                rightIndex--;
            } else {
                //  偶数 和 偶数
                rightIndex--;
            }
        }
        return nums;
    }
}

你可能感兴趣的:(LeetCode 每日一题 [53] 调整数组顺序使奇数位于偶数前面)