我试图解决的问题如下: -我们如何交换数组中的两个元素?
鉴于整数长度为3的阵列,其中所述元件返回一个数组“向左旋转”,所以{1,2,3}产量{2,3, 1}
我想出了下面的代码: -
public int[] rotateLeft3(int[] nums) {
for(int i=0;i<2;i++)
swap(nums[i],nums[i+1]);
return nums;
}
public void swap(int a,int b)
{
int temp = a;
a = b;
b= temp;
}
但是,它没有成功运行。在C++的情况下,我可以将引用作为参数传递,问题将被排序,那么为什么不在这里发生?
下面的代码工作: -
public int[] rotateLeft3(int[] nums) {
int temp = nums[0];
nums[0] = nums[1];
nums[1] = temp;
temp = nums[1];
nums[1] = nums[2];
nums[2] = temp;
return nums;
}
但这种代码是完整的蛮力写作,我不喜欢很喜欢。你能否建议我如何使第一种方法奏效?
这与插入排序中使用的逻辑相同(移位元素)。我本可以使用这个。 – kusur