2013-12-19 40 views
1

我试图解决的问题如下: -我们如何交换数组中的两个元素?

鉴于整数长度为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; 
} 

但这种代码是完整的蛮力写作,我不喜欢很喜欢。你能否建议我如何使第一种方法奏效?

回答

3

如果希望不受到尺寸的限制旋转,尝试:

public int[] rotateLeft(int[] nums){ 
    if(nums.length == 0) 
    return new int[0]; 

    int temp = nums[0]; 
    //This loop starts at index 1 because we are moving 
    // elements left, and 0 can't move left. 
    for(int index = 1; index < nums.length; index++){ 
    nums[index-1] = nums[index]; 
    } 

    nums[nums.length-1] = temp; 
} 
+0

这与插入排序中使用的逻辑相同(移位元素)。我本可以使用这个。 – kusur

6

java方法调用中的所有参数都是按值传递的。你需要传入数组和你想交换的两个索引。

public void swap(int[] array, int a,int b) 
{ 
int temp = array[a]; 
array[a] = array[b]; 
array[b]= temp; 
} 
4

正如你所说的那样,问题是通过引用传递的,C做到了 - Java没有。尽管如此,还有很多其他方法可以达到相同的目的。

最简单的方法是将数组和两个索引传递给交换函数,而不是该索引处数组的内容。

3

,你也可以使用XOR交换而不temp变量;)

public void swap(int[] array, int ind1, int ind2) { 
array[ind1] ^= array[ind2] 
array[ind1] ^= (array[ind2] ^= array[ind1]) 
} 
2

当你调用交换方法,您传递数组内的值,但该方法不会返回a和b值。是的,这可以通过使用指针在C/C++中完成,但是java没有。

Xynariz的代码提供了一种不局限于数组大小的移位方式。

0

您可以创建一个单一的线使用模式的交换功能,但调用格式不典型:

public int[] rotateLeft3(int[] nums) { 
    for(int i=0;i<2;i++) 
    nums[i+1] = swap(nums[i], nums[i]=nums[i+1]); 
    return nums; 
} 

// swaps any number of same type objects 
public <T> T swap(T... args) { 
    // usage: z = swap(a, a=b, b=c, ... y=z); 
    return args[0]; 
} 

这工作,因为第一个参数传递到交换的任务中的其余部分发生前参数。