gpt4 book ai didi

java - Codingbat fix45 有更简单的解决方案吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:31 26 4
gpt4 key购买 nike

我正在尝试解决这个 CodingBat 问题:

(This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 4 is immediately followed by a 5. Do not move the 4's, but every other number may move. The array contains the same number of 4's and 5's, and every 4 has a number after it that is not a 4. In this version, 5's may appear anywhere in the original array.

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;

}

最佳答案

每次找到 4 时都从数组的一端重新开始搜索合适的 5 似乎很浪费。数组的一部分已经被扫描并且已知不包含可以移动的 5。这是 O(n) 的时间和 O(1) 的空间。

    public static int[] fix45(int[] nums) {

int j = 0;
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == 4 && nums[i + 1] != 5) {
/*
* Need to find the next movable 5 That means an element that is 5 and
* either is the first element or is preceded by anything other than 4
*/
while (nums[j] != 5 || (j != 0 && nums[j - 1] == 4)) {
j++;
}
nums[j] = nums[i + 1];
nums[i + 1] = 5;
}
}
return nums;
}

关于java - Codingbat fix45 有更简单的解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com