gpt4 book ai didi

java - fix34codingbat java——为什么这不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:51 24 4
gpt4 key购买 nike

Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3, and a 3 appears in the array before any 4. Here is the link .

下面是我的代码。

public int[] fix34(int[] nums) {
for(int k = 0; k<nums.length; k++)
{
if(nums[k] == 3)
{
int jay = nums[k+1];
for(int j = 0; j<nums.length; j++)
{
if(nums[j] == 4)
{
nums[k+1] = nums[j];
nums[j] = jay;
}
}
}
}
return nums;

我想让它这样,如果我们找到数字 3,我们继续寻找 4(可能在 3 之前或之后),并将 4 与紧随 3 后面的数字交换。但是,由于它不适用于所有情况,我猜测我的代码并没有完全做到这一点。或者说,这是一个逻辑错误吗?任何帮助将不胜感激! (我知道还有一些其他解决方案,但我想确切地了解我的解决方案出了什么问题。)

最佳答案

我保留了你的逻辑并做了一些改变。
找到 4 并进行交换后,内部循环需要一个 break
另外,在寻找 4 时,绕过 3 之后的任何 4:

public static int[] fix34(int[] nums) {
for(int k = 0; k < nums.length; k++) {
if(nums[k] == 3) {
int jay = nums[k+1];
if (jay != 4) {
for (int j = 1; j < nums.length; j++) {
if (nums[j] == 4 && nums[j - 1] != 3) {
nums[k + 1] = 4;
nums[j] = jay;
break;
}
}
}
}
}
return nums;
}

public static void main(String[] args) {
int[] array1 = {1, 3, 1, 4};
int[] array2 = {1, 3, 1, 4, 4, 3, 1};
int[] array3 = {3, 2, 2, 4};

System.out.println(Arrays.toString(array1) + "-->" + Arrays.toString(fix34(array1)));
System.out.println(Arrays.toString(array2) + "-->" + Arrays.toString(fix34(array2)));
System.out.println(Arrays.toString(array3) + "-->" + Arrays.toString(fix34(array3)));
}

将打印

[1, 3, 1, 4]-->[1, 3, 4, 1]
[1, 3, 1, 4, 4, 3, 1]-->[1, 3, 4, 1, 1, 3, 4]
[3, 2, 2, 4]-->[3, 4, 2, 2]

关于java - fix34codingbat java——为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53656195/

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