void swapEven(int[]数组)
在给定的整数数组中,nums 交换第一个和最后一个数组元素、第二个和倒数第二个数组元素的值,依此类推,如果这两个交换值都是偶数。
请注意,输入数组可能为空。
示例 代码示例:
... int[] 数组 = new int[]{ 10, 5, 3, 4 }; .... 输出:
[4,5,3,10]
我的代码:
public class FirstProgram {
public static void main(String[] args) {
int[] myArray = new int[]{100, 2, 3, 45, 33, 8, 4, 54};
swapEven(myArray);
}
public static void swapEven(int[] array) {
// TODO: Implement this method.
int temp, firstNumIndex, secondNumIndex, counter = 1;
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
firstNumIndex = i;
if (array[array.length - counter] % 2 == 0) {
secondNumIndex = array.length - counter;
temp = array[firstNumIndex];
array[firstNumIndex] = array[secondNumIndex];
array[secondNumIndex] = temp;
}
}
counter++;
}
} else {
array = new int[]{};
System.out.println(Arrays.toString(array));
}
}
}
试图找出为什么它给我相同的数组作为输入。它不交换数组。 我是否返回了错误的数组,是否应该创建第二个数组来添加值然后重新调整?
当前实现的问题是它没有正确配对交换元素。循环和计数器变量不同步,以确保正确选择对(第一-最后、第二-第二最后等)。
此外,您不需要创建第二个数组;您可以使用数组开头和结尾的几个指针交换元素:
import java.util.Arrays;
class FirstProgram {
public static void main(String[] args) {
int[] myArray = new int[] { 100, 2, 3, 45, 33, 8, 4, 54 };
System.out.printf("Before swapEven: %s%n", Arrays.toString(myArray));
swapEven(myArray);
System.out.printf("After swapEven: %s%n", Arrays.toString(myArray));
}
public static void swapEven(int[] array) {
// No swapping needed for empty or single-element arrays.
if (array == null || array.length < 2) {
return;
}
int left = 0;
int right = array.length - 1;
while (left < right) {
if (array[left] % 2 == 0 && array[right] % 2 == 0) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
left++;
right--;
}
}
}
输出:
Before swapEven: [100, 2, 3, 45, 33, 8, 4, 54]
After swapEven: [54, 4, 3, 45, 33, 8, 2, 100]