用 C++ 找到两个数组之间的兼容性差异
假设有两个朋友,现在他们想测试一下他们的默契度。因此,他们将检查他们有多少默契。假设有 n 个数,编号为 1..n。他们被要求对这些数字进行排序。他们必须找到他们之间的默契度差异。默契度差异基本上是指他们给出的相同电影的相对排名中的不匹配数量。因此,如果 A = [3, 1, 2, 4, 5],并且 B = [3, 2, 4, 1, 5],则输出将为 2。默契度差异为 2,因为第一个将电影 1 排在 2 和 4 之前,但另一个则将电影 1 排在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP