输入一个整数数组,输出奇偶数相间排列的数组
2021-05-07 07:28
标签:abs 抛出异常 str 输入 一个 奇数 form OLE format 输入一个整数数组,输出奇偶数相间排列的数组 标签:abs 抛出异常 str 输入 一个 奇数 form OLE format 原文地址:https://www.cnblogs.com/optor/p/13185029.html前提条件
思路
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
System.out.println(Arrays.toString(oddEvenHandle(new int[]{2, 2, 3})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 4})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 8})));
System.out.println(Arrays.toString(oddEvenHandle(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 8, 8})));
}
private static int[] oddEvenHandle(int[] array) {
if (array == null || array.length == 0) {
return array;
}
int oddCount = 0, evenCount = 0;
for (int ele : array) {
if (ele % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
if (Math.abs(oddCount - evenCount) > 1) {
throw new IllegalArgumentException(String.format("oddCount = %d, evenCount = %d", oddCount, evenCount));
}
boolean oddHead = false;
if (oddCount >= evenCount) {
oddHead = true;
}
int oddPoint = 0, evenPoint = 0;
for (int i = 0; i
文章标题:输入一个整数数组,输出奇偶数相间排列的数组
文章链接:http://soscw.com/index.php/essay/83575.html