在这里我试图交换' 9'的位置,所以它恰好在' 4'之后。
输入:int[] nums1 = { 1, 4, 1, 9 };
输出:[1, 4, 9, 1]
代码:
int loc4 = 0;
int temp = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
loc4 = i;
}
if (arr[i] == 9) {
for (int j = i; j > 0; j--) {
temp = arr[i];
arr[i] = arr[loc4 + 1];
arr[loc4 + 1] = temp;
}
}
}
此代码的问题在于,一旦有多个4和9,它就会忽略重复项。
所以我尝试添加重复计数和continue
语句,因为当rep计数大于1时,但这似乎不起作用?
int loc4 = 0;
int temp = 0;
int rep = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
loc4 = i;
rep++;
}
if (arr[i] == 9) {
for (int j = i; j > 0; j--) {
temp = arr[i];
arr[i] = arr[loc4 + 1];
arr[loc4 + 1] = temp;
if (rep > 1)
continue;
}
}
}
所以我的输入是:int[] nums2 = { 1, 4, 1, 9, 9, 4, 1 };
我的输出应为:[1,4,9,1,1,4,9]
我得到的是:[1, 4, 9, 1, 9, 4, 1]
请注意,如果有单数4和9,或者它们已经按顺序排列,则不会发生任何事情。
答案 0 :(得分:0)
首先,你应该检查继续做什么:What is the "continue" keyword and how does it work in Java?
这是一种与您的算法不同的算法。 (我希望我没有留下任何边缘案例)
public static void foo(int[] arr)
{
int i = 0;
while(i != arr.Length)
{
if(arr[i] == 4 || arr[i] == 9)
{
if(arr[i] == 4)//find the next 9 and swap with arr[i+1]
{
int j = i+1;
while(arr[j] != 9 && j < arr.Length)
{
j++;//inc j while arr[j] is not 9
}
if(arr[j] == 9)
{
int temp = arr[i + 1];
arr[i + 1] = arr[j];
arr[j] = temp;
i += 2; //skip over '9' that just replaced
}
else
{
i++;// didn't find '9' so move on to next index
}
}
else if(arr[i] == 9) //find the next '4' and swap with the number that comes after it, and don't increament i if found..
{
int j = i + 1;
while (arr[j] != 4 && j < arr.Length)
{
j++;//inc j while arr[j] is not '4'
}
if(arr[j] == 4 && j < arr.Length)
{
int temp = arr[i];
arr[i] = arr[j+1];
arr[j+1] = temp;
}
else
{
i++; // didn't find '4' so move on to next index
}
}
}
else // not 4 or 9
{
i++; //move on to next index
}
}
}