我正在尝试解决这个 CodingBat 问题:
(这是 fix34 问题的一个稍微困难的版本。)返回一个包含与给定数组完全相同的数字的数组,但重新排列,以便每个 4 紧跟一个 5。不要移动 4,而是每隔一个数字可能会移动。该数组包含相同数量的 4 和 5,并且每个 4 后面都有一个不是 4 的数字。在此版本中,5 可能出现在原始数组中的任何位置。
fix45({5, 4, 9, 4, 9, 5}) → {9, 4, 5, 4, 5, 9}
fix45({1, 4, 1, 5}) → {1, 4, 5, 1}
fix45({1, 4, 1, 5, 5, 4, 1}) → {1, 4, 5, 1, 1, 4, 5}
我最初使用的方法通过了所有站点测试,但我认为它不适用于更长的数组。初始方法使用了 2 个循环,并且没有使用新数组。我创建了一个解决方案,它引入了一个新数组和第三个嵌套循环,我相信它适用于所有问题实例。但是,该站点声明本节中的问题可以通过 2 个循环来解决,所以我想知道是否真的有一个 2 循环解决方案适用于任何问题实例。这是问题和我的 3 循环解决方案:
public int[] fix45(int[] nums) {
int[] locations = {-1};
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == 4) {
JLoop:
for (int j = nums.length-1; j >= 0; --j) {
if (nums[j] == 5) {
for (int k = locations.length-1; k>=0 ; --k) {
if (locations[k] == j) {
continue JLoop;
}
}
nums[j] = nums[i + 1];
nums[i + 1] = 5;
locations[locations.length - 1] = i+1;
locations = java.util.Arrays.copyOf(locations,
locations.length + 1);
locations[locations.length-1] = -1;
break;
}
}
}
}
return nums;
}