在C ++中找到两个数组之间的兼容性差异
考虑有两个朋友,现在他们想测试他们的联系。因此,他们将检查它们之间的兼容性。给定数字n,从1..n开始编号。然后要求他们对数字进行排名。他们必须找到它们之间的兼容性差异。兼容性差异基本上是由他们给出的同一电影的相对排名中的不匹配数。因此,如果A=[3,1,2,4,5],而B=[3,2,4,1,5],则输出将为2。兼容性差异为2,因为第一个将电影排在第一2和4,但其他人排在后面。
为了解决这个问题,当当前元素相同时,我们将遍历两个数组,然后什么也不做。然后找到A和B的下一个位置,使位置为j,将B[j]逐个移动到B[i]
示例
#include<iostream> using namespace std; int getArrayDiff(int A[], int B[], int n) { int result = 0; for (int i = 0; i < n; i++) { if (A[i] != B[i]) { int j = i + 1; while (A[i] != B[j]) j++; while (j != i) { swap(B[j], B[j - 1]); j--; result++; } } } return result; } int main() { int A[] = { 3, 1, 2, 4, 5 }; int B[] = { 3, 2, 4, 1, 5 }; int n = sizeof(A)/sizeof(A[0]); cout << "Compatibility difference: " << getArrayDiff(A, B, n); }
输出结果
Compatibility difference: 2