Java - 数组练习题4 - 奇偶互换

  • 题目:
    • 有一个数组[1,2,3,4,5,6,7,8,8,9,10,21,20,12], 将左边起找到的第一个偶数和右边起找到的第一个奇数互换位置
    • 结果 {1,21,3,9,5,7,68,8,4,10,2,20,12}
package com.Alibaba;

import java.util.Arrays;

public class Test08 {
    public static void main(String[] args) {
        //1.[1,2,3,4,5,6,7,8,8,9,10,21,20,12]
        int[] srcArr = {1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 21, 20, 12};
        int left = 0;
        int right = srcArr.length - 1;
        while (left < right) {
            while (srcArr[left] % 2 != 0 && left < right) {
                left++;
            }
            while (srcArr[right] % 2 == 0 && left < right) {
                right--;
            }
            int temp = srcArr[left];
            srcArr[left] = srcArr[right];
            srcArr[right] = temp;
        }
        System.out.println(Arrays.toString(srcArr));
        System.out.println("===============================================");
    }
}

你可能感兴趣的:(JAVA,java,开发语言,leetcode)