如何解决如何在我的数组中交换两个数字index1和index2
这是我的代码,我对如何将index1处的数组值与index2处的数组值交换感到困惑
public static void swapByIndex(int myArray[],int index1,int index2) {
int position1 = myArray[index1];
int position2 = myArray[index2];
for(int i = 0; i < myArray.length; i++) {
if(i == position1) {
myArray[i] = position2;
}
if(i == position2) {
myArray[i] = position1;
}
System.out.print(myArray[i] + " ");
}
}
解决方法
这是非常简单且常见的方法:
public static void swapByIndex(int myArray[],int index1,int index2) {
int temp = myArray[index1];
myArray[index1] = myArray[index2];
myArray[index2] = temp;
}
P.S。该解决方案的时间复杂度为O(1),但您的时间复杂度为O(n)。
,执行交换的经典方法是简单地使用一个临时的int变量在更改一个头寸时获取它的值,因此当您要将其分配给另一个头寸时仍然可以使用它
public static void swapByIndex(int myArray[],int index2) {
int temp = myArray[index1];
myArray[index1] = myArray[index2];
myArray[index2] = temp;
}
,
交换元素时不需要迭代整个数组。您只需交换第三个变量并在其中存储第一个索引的值即可交换它们。然后,将第二个索引值存储在第一个索引中。之后,将第三个变量中的值存储在第二个索引中。
public static void swapByIndex(int myArray[],int index2) {
int temp = myArray[index1];
myArray[index1] = myArray[index2];
myArray[index2] = temp;
}
,
这里是交换工作原理的快速解释。
public static void swapByIndex(int myArray[],int index2) {
int position1 = myArray[index1];
int position2 = myArray[index2];
// At this point,you already know both the indexes and the values.
// You can just assign the values directly.
myArray[index1] = position2;
myArray[index2] = position1;
}
现在,一旦有了这个,您可能会注意到我们只需要将一个值存储在一个临时变量中。我们可以将其进一步简化为更常见的形式:
public static void swapByIndex(int myArray[],int index2) {
int position1 = myArray[index1];
// Overwrite the value stored at index 1
myArray[index1] = myArray[index2];
// Use the stored value to then fill in the second index
myArray[index2] = position1;
}
这是我们获得交换功能最常见版本的方式。
public static void swap(int[] array,int a,int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
虽然我不建议您开始学习Java,但也可以使用适用于任何类型数组的通用版本。
public static <T> void swap(T[] array,int b) {
T tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。