我用Java编写了这段代码,以便进行最小交换,
由于第二个列表保证已排序,因此我们可以查找其中每个元素并从第一个列表中找到其索引,然后在当前索引元素和我们找到的元素之间进行交换。
更新:我修改了findLastElementIndex函数,它会根据list2检查交换后的元素是否在正确的索引位置。
public class Testing {
private static String[] unorderedList = {"Z", "C", "A", "B", "A", "K"};
private static String[] orderedList = {"A", "A", "B", "C", "K", "Z"};
private static int numberOfSwaps;
public static void main(String[] args) {
for (int i = 0; i < unorderedList.length; i++) {
if (!unorderedList[i].equals(orderedList[i])) {
int index = findElementToSwapIndex(i, orderedList[i]);
swapElements(unorderedList, i, index);
}
}
System.out.println(numberOfSwaps);
}
private static void swapElements(String[] list, int indexOfFirstElement, int IndexOfSecElement) {
String temp = list[indexOfFirstElement];
list[indexOfFirstElement] = list[IndexOfSecElement];
list[IndexOfSecElement] = temp;
numberOfSwaps++;
}
private static int findElementToSwapIndex(int currentIndexOfUnorderedList , String letter) {
int lastElementToSwapIndex = 0;
for (int i = 0; i < unorderedList.length; i++) {
if (unorderedList[i].equals(letter)) {
lastElementToSwapIndex = i;
if(unorderedList[currentIndexOfUnorderedList].equals(orderedList[lastElementToSwapIndex])){
return lastElementToSwapIndex;
}
}
}
return lastElementToSwapIndex;
}
}
这段代码的最小交换次数与https://dev59.com/6GUp5IYBdhLWcg3woonS#40507589中的相同。
希望这能对你有所帮助。
0
开始,属于此处的元素是A
,在list1
中进行线性搜索以查找A
,返回索引2
。交换索引0
和2
,以此类推。 - Hatefiend