给定两个长度为N 的数组arr[]和brr[] ,任务是找到所需的相同索引元素的最小交换次数,这样的元素至少出现在数组arr[]中的索引的一半,即多数元素.如果不可能获得这样的安排,则打印“-1” 。
例子:
Input: arr[] = {3, 2, 1, 4, 9}, brr[] = {5, 5, 3, 5, 3}
Output: 2
Explanation:
Following are the swaps required:
Swap 1: Swapping arr[1] and brr[1] modifies arr[] to {3, 2, 3, 4, 9} and brr[] to {5, 5, 1, 5, 3}.
Swap 2: Swapping arr[5] and brr[5] modifies arr[] to {3, 2, 3, 4, 3} and brr[] to {5, 5, 1, 5, 9}.
Therefore, the total number of swaps required is 2.
Input: arr[] = {2, 4, 2}, brr[] = {1, 2, 9}
Output: 0
处理方法:按照以下步骤解决上述问题:
- 将变量res初始化为 INT_MAX,用于存储所需的最小交换。
- 使用散列法找到数组 a[] 和 b[] 元素的频率计数,并将其分别存储在映射A和B 中。
- 创建一个大小为2*N的数组crr[]来存储数组arr[]和brr[] 中的所有元素。
- 使用变量i遍历数组crr[]并执行以下操作:
- 如果映射A中crr[i]的频率至少为N/2,则所需的最小交换为0并跳出循环并打印0 。
- 如果映射A和B中crr[i]的频率之和至少为N/2,则将res更新为res和(N/2 – A[crr[i]]) 的最小值。
- 经过以上步骤,如果res的值仍然是INT_MAX ,则打印“-1” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that counts the minimum
// number of swaps required to make
// half of the element same in a[]
int minMoves(int a[], int b[], int n)
{
// Stores frequency of elements in a[]
// Stores frequency of elements in b[]
unordered_map A, B;
// Stores all elements from both arrays
vector c;
// Find the maximum occurrence
// required
int maxOccur = ceil(floor(n)
/ (2 * 1.0));
for (int i = 0; i < n; ++i) {
c.push_back(a[i]);
c.push_back(b[i]);
A[a[i]]++;
// If a[i] == b[i], then no need
// of incrementing in map B
if (b[i] != a[i]) {
B[b[i]]++;
}
}
// Store the minimum number of swaps
int res = INT_MAX;
for (int i = 0; i < c.size(); ++i) {
// Frequency of c[i] in array a
int x = A];
// Frequency of c[i] in array b
int y = B];
// Check the frequency condition
if ((x + y) >= maxOccur) {
// if c[i] is present at
// least half times in array
// a[], then 0 swaps required
if (x >= maxOccur) {
return 0;
}
// maxOccur - x is the count
// of swaps needed to make
// c[i] the majority element
else {
res = min(res, maxOccur - x);
}
}
}
// If not possible
if (res == INT_MAX) {
return -1;
}
// Otherwise
else
return res;
}
// Driver Code
int main()
{
// Given arrays a[] and b[]
int arr[] = { 3, 2, 1, 4, 9 };
int brr[] = { 5, 5, 3, 5, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
cout << minMoves(arr, brr, N);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class Main{
// Function that counts the minimum
// number of swaps required to make
// half of the element same in a[]
public static int minMoves(int a[],
int b[],
int n)
{
// Stores frequency of elements
// in a[]
// Stores frequency of elements
// in b[]
HashMap A =
new HashMap<>();
HashMap B =
new HashMap<>();
// Stores all elements from
// both arrays
Vector c =
new Vector();
// Find the maximum occurrence
// required
int maxOccur = (int)Math.ceil(
(int)Math.floor(n) /
(2 * 1.0));
for (int i = 0; i < n; ++i)
{
c.add(a[i]);
c.add(b[i]);
if(A.containsKey(a[i]))
{
A.replace(a[i],
A.get(a[i]) + 1);
}
else
{
A.put(a[i], 1);
}
// If a[i] == b[i], then no need
// of incrementing in map B
if (b[i] != a[i])
{
if(B.containsKey(b[i]))
{
B.replace(b[i],
B.get(b[i]) + 1);
}
else
{
B.put(b[i], 1);
}
}
}
// Store the minimum number
// of swaps
int res = Integer.MAX_VALUE;
for (int i = 0; i < c.size(); ++i)
{
// Frequency of c[i] in array a
int x = 0;
if(A.containsKey(c.get(i)))
{
x = A.get(c.get(i));
}
// Frequency of c[i] in array b
int y = 0;
if(B.containsKey(c.get(i)))
{
y = B.get(c.get(i));
}
// Check the frequency
// condition
if ((x + y) >= maxOccur)
{
// if c[i] is present at
// least half times in array
// a[], then 0 swaps required
if (x >= maxOccur)
{
return 0;
}
// maxOccur - x is the count
// of swaps needed to make
// c[i] the majority element
else
{
res = Math.min(res,
maxOccur - x);
}
}
}
// If not possible
if (res == Integer.MAX_VALUE)
{
return -1;
}
// Otherwise
else
return res;
}
// Driver code
public static void main(String[] args)
{
// Given arrays a[] and b[]
int arr[] = {3, 2, 1, 4, 9};
int brr[] = {5, 5, 3, 5, 3};
int N = arr.length;
// Function Call
System.out.println(minMoves(arr, brr, N));
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for the above approach
from math import ceil, floor
import sys
# Function that counts the minimum
# number of swaps required to make
# half of the element same in a[]
def minMoves(a, b, n):
# Stores frequency of elements in a[]
# Stores frequency of elements in b[]
A, B = {}, {}
# Stores all elements from both arrays
c = []
# Find the maximum occurrence
# required
maxOccur = ceil(floor(n) / (2 * 1.0))
for i in range(n):
c.append(a[i])
c.append(b[i])
A[a[i]] = A.get(a[i], 0) + 1
# If a[i] == b[i], then no need
# of incrementing in map B
if (b[i] != a[i]):
B[b[i]] = B.get(b[i], 0) + 1
# Store the minimum number of swaps
res = sys.maxsize
for i in range(len(c)):
# Frequency of c[i] in array a
x, y = 0, 0
if c[i] in A:
x = A]
# Frequency of c[i] in array b
if c[i] in B:
y = B]
# Check the frequency condition
if ((x + y) >= maxOccur):
# If c[i] is present at
# least half times in array
# a[], then 0 swaps required
if (x >= maxOccur):
return 0
# maxOccur - x is the count
# of swaps needed to make
# c[i] the majority element
else:
res = min(res, maxOccur - x)
# If not possible
if (res == sys.maxsize):
return -1
# Otherwise
else:
return res
# Driver Code
if __name__ == '__main__':
# Given arrays a[] and b[]
arr = [ 3, 2, 1, 4, 9 ]
brr = [ 5, 5, 3, 5, 3 ]
N = len(arr)
# Function Call
print(minMoves(arr, brr, N))
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Function that counts the minimum
// number of swaps required to make
// half of the element same in []a
public static int minMoves(int []a,
int []b,
int n)
{
// Stores frequency of elements
// in []a
// Stores frequency of elements
// in []b
Dictionary A = new Dictionary();
Dictionary B = new Dictionary();
// Stores all elements from
// both arrays
List c = new List();
// Find the maximum occurrence
// required
int maxOccur = (int)(Math.Ceiling(
(int)(Math.Floor(
(double)n)) / (2 * 1.0)));
for(int i = 0; i < n; ++i)
{
c.Add(a[i]);
c.Add(b[i]);
if (A.ContainsKey(a[i]))
{
A[a[i]] = A[a[i]] + 1;
}
else
{
A.Add(a[i], 1);
}
// If a[i] == b[i], then no need
// of incrementing in map B
if (b[i] != a[i])
{
if (B.ContainsKey(b[i]))
{
B[b[i]]++;
}
else
{
B.Add(b[i], 1);
}
}
}
// Store the minimum number
// of swaps
int res = int.MaxValue;
for(int i = 0; i < c.Count; ++i)
{
// Frequency of c[i] in array a
int x = 0;
if (A.ContainsKey(c[i]))
{
x = A];
}
// Frequency of c[i] in array b
int y = 0;
if (B.ContainsKey(c[i]))
{
y = B];
}
// Check the frequency
// condition
if ((x + y) >= maxOccur)
{
// If c[i] is present at
// least half times in array
// []a, then 0 swaps required
if (x >= maxOccur)
{
return 0;
}
// maxOccur - x is the count
// of swaps needed to make
// c[i] the majority element
else
{
res = Math.Min(res,
maxOccur - x);
}
}
}
// If not possible
if (res == int.MaxValue)
{
return -1;
}
// Otherwise
else
return res;
}
// Driver code
public static void Main(String[] args)
{
// Given arrays []a and []b
int []arr = { 3, 2, 1, 4, 9 };
int []brr = { 5, 5, 3, 5, 3 };
int N = arr.Length;
// Function Call
Console.WriteLine(minMoves(arr, brr, N));
}
}
// This code is contributed by Princi Singh
Javascript
输出:
2
时间复杂度: O(N)
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。