C++程序通过旋转最大化给定数组中对应相同元素的计数
给定两个包含N个整数的数组arr1[]和arr2[] ,并且数组arr1[]具有不同的元素。任务是通过对数组arr1[]执行循环左移或右移来找到给定数组中对应相同元素的最大计数。
例子:
Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9, 5, 6 }
Output: 5
Explanation:
By performing cyclic left shift on array arr1[] by 1.
Updated array arr1[] = {7, 3, 9, 5, 6}.
This rotation contains a maximum number of equal elements between array arr1[] and arr2[].
Input: arr1[] = {1, 3, 2, 4}, arr2[] = {4, 2, 3, 1}
Output: 2
Explanation:
By performing cyclic left shift on array arr1[] by 1.
Updated array arr1[] = {3, 2, 4, 1}
This rotation contains a maximum number of equal elements between array arr1[] and arr2[].
方法:这个问题可以使用贪心方法来解决。以下是步骤:
- 将数组arr2[]的所有元素的位置存储在一个数组中(比如store[] )。
- 对于数组arr1[]中的每个元素,执行以下操作:
- 找出arr2[]中当前元素的位置与arr1[]中的位置之间的差异(比如diff )。
- 如果diff小于 0 则将 diff 更新为(N – diff) 。
- 将当前差异差异的频率存储在地图中。
- 经过上述步骤,map 中存储的最大频率是在arr1[]上旋转后相等元素的最大数量。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function that prints maximum
// equal elements
void maximumEqual(int a[], int b[],
int n)
{
// Vector to store the index
// of elements of array b
vector store(1e5);
// Storing the positions of
// array B
for (int i = 0; i < n; i++) {
store[b[i]] = i + 1;
}
// frequency array to keep count
// of elements with similar
// difference in distances
vector ans(1e5);
// Iterate through all element in arr1[]
for (int i = 0; i < n; i++) {
// Calculate number of
// shift required to
// make current element
// equal
int d = abs(store[a[i]]
- (i + 1));
// If d is less than 0
if (store[a[i]] < i + 1) {
d = n - d;
}
// Store the frequency
// of current diff
ans[d]++;
}
int finalans = 0;
// Compute the maximum frequency
// stored
for (int i = 0; i < 1e5; i++)
finalans = max(finalans,
ans[i]);
// Printing the maximum number
// of equal elements
cout << finalans << "
";
}
// Driver Code
int main()
{
// Given two arrays
int A[] = { 6, 7, 3, 9, 5 };
int B[] = { 7, 3, 9, 5, 6 };
int size = sizeof(A) / sizeof(A[0]);
// Function Call
maximumEqual(A, B, size);
return 0;
}
5
时间复杂度: O(N)
辅助空间: O(N)
有关更多详细信息,请参阅有关通过旋转最大化给定数组中相应相同元素的计数的完整文章!