📌  相关文章
📜  使任何两个数组元素相等的最小按位与运算

📅  最后修改于: 2021-10-27 08:35:52             🧑  作者: Mango

给定一个大小为“n”的整数数组和一个整数“k”,
我们可以在任何数组元素和 ‘k’ 之间执行任意次数的按位与运算。
任务是打印使数组的任何两个元素相等所需的最少此类操作数。
如果在执行上述操作后无法使数组的任何两个元素相等,则打印“-1”。
例子:

方法:
关键的观察是,如果可以制作所需的数组,那么答案将是“0”、“1”或“2”。它永远不会超过“2”。

  • 如果数组中已经有相等的元素,则答案为“0”。
  • 如果答案是“1”,我们将创建一个新数组 b,其中包含 b[i] = (a[i]&K),
    现在,对于每个 a[i],我们将检查是否存在任何索引 ‘j’ 使得 i!=j 和 a[i]=b[j]。
    如果是,那么答案将是“1”。
  • 如果答案是“2”,我们将检查新数组 b 中的索引“i”,
    如果存在任何索引 ‘j’ 使得 i != j 和 b[i] = b[j]。
    如果是,那么答案将是“2”。
  • 如果不满足上述任何条件,则答案将为“-1”。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to count the
// minimum operations required.
int minOperations(int a[], int n, int K)
{
    unordered_map map;
    for (int i = 0; i < n; i++) {
 
        // check if the initial array
        // already contains an equal pair
        if (map[a[i]])
            return 0;
        map[a[i]] = true;
    }
     
    // create new array with AND operations
    int b[n];
    for (int i = 0; i < n; i++)
        b[i] = a[i] & K;   
 
    // clear the map
    map.clear();
 
    // Check if the solution
    // is a single operation
    for (int i = 0; i < n; i++) {
 
        // If Bitwise operation between
        //'k' and a[i] gives
        // a number other than a[i]
        if (a[i] != b[i])
            map[b[i]] = true;
    }
 
    // Check if any of the a[i]
    // gets equal to any other element
    // of the array after the operation.
    for (int i = 0; i < n; i++)
 
        // Single operation
        // will be enough
        if (map[a[i]])
           return 1;
 
    // clear the map
    map.clear();
 
    // Check if the solution
    // is two operations
    for (int i = 0; i < n; i++) {
 
        // Check if the array 'b'
        // contains duplicates
        if (map[b[i]])
           return 2;
 
        map[b[i]] = true;
    }
 
    // otherwise it is impossible to
    // create such an array with
    // Bitwise AND operations
    return -1;
}
 
// Driver code
int main()
{
 
    int K = 3;
    int a[] = { 1, 2, 3, 7 };
    int n = sizeof(a)/sizeof(a[0]);
 
    // Function call to compute the result
    cout << minOperations(a, n, K);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class geeks
{
 
    // Function to count the
    // minimum operations required.
    public static int minOperations(int[] a, int n, int K)
    {
        HashMap map = new HashMap<>();
         
        for (int i = 0; i < n; i++)
        {
 
            // check if the initial array
            // already contains an equal pair
            // try-catch is used so that
            // nullpointer exception can be handeled
            try
            {
                if (map.get(a[i]))
                    return 1;
            }
            catch (Exception e)
            {
                //TODO: handle exception
            }
             
            try
            {
                map.put(a[i], true);
            } catch (Exception e) {}
        }
 
        // create new array with AND operations
        int[] b = new int[n];
        for (int i = 0; i < n; i++)
            b[i] = a[i] & K;
 
        // clear the map
        map.clear();
 
        // Check if the solution
        // is a single operation
        for (int i = 0; i < n; i++)
        {
 
            // If Bitwise operation between
            // 'k' and a[i] gives
            // a number other than a[i]
            if (a[i] != b[i])
            {
                try
                {
                    map.put(b[i], true);
                }
                catch (Exception e) {}
            }
        }
 
        // Check if any of the a[i]
        // gets equal to any other element
        // of the array after the operation.
        for (int i = 0; i < n; i++)
        {
 
            // Single operation
            // will be enough
            try
            {
                if (map.get(a[i]))
                    return 1;
            }
            catch (Exception e)
            {
                //TODO: handle exception
            }
        }
 
        // clear the map
        map.clear();
 
        // Check if the solution
        // is two operations
        for (int i = 0; i < n; i++)
        {
 
            // Check if the array 'b'
            // contains duplicates
            try
            {
                if (map.get(b[i]))
                    return 2;
            }
            catch (Exception e)
            {
                //TODO: handle exception
            }
 
            try
            {
                map.put(b[i], true);
            }
            catch (Exception e)
            {
                //TODO: handle exception
            }
        }
 
        // otherwise it is impossible to
        // create such an array with
        // Bitwise AND operations
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int K = 3;
        int[] a = { 1, 2, 3, 7 };
        int n = a.length;
 
        // Function call to compute the result
        System.out.println(minOperations(a, n, K));
    }
}
 
// This code is contributed by
// sanjeev2552


Python3
# Python3 implementation of the approach
from collections import defaultdict
 
# Function to count the minimum
# operations required.
def minOperations(a, n, K):
 
    Map = defaultdict(lambda:False)
    for i in range(0, n):
 
        # check if the initial array
        # already contains an equal pair
        if Map[a[i]] == True:
            return 0
        Map[a[i]] = True
     
    # create new array with AND operations
    b = []
    for i in range(0, n):
        b.append(a[i] & K)
 
    # clear the map
    Map.clear()
 
    # Check if the solution
    # is a single operation
    for i in range(0, n):
     
        # If Bitwise operation between
        #'k' and a[i] gives
        # a number other than a[i]
        if a[i] != b[i]:
            Map[b[i]] = True
 
    # Check if any of the a[i]
    # gets equal to any other element
    # of the array after the operation.
    for i in range(0, n):
 
        # Single operation
        # will be enough
        if Map[a[i]] == True:
            return 1
 
    # clear the map
    Map.clear()
 
    # Check if the solution
    # is two operations
    for i in range(0, n):
     
        # Check if the array 'b'
        # contains duplicates
        if Map[b[i]] == True:
            return 2
 
        Map[b[i]] = True
     
    # otherwise it is impossible to
    # create such an array with
    # Bitwise AND operations
    return -1
 
# Driver code
if __name__ == "__main__":
 
    K = 3
    a = [1, 2, 3, 7]
    n = len(a)
 
    # Function call to compute the result
    print(minOperations(a, n, K))
 
# This code is contributed by Rituraj Jain


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
     
    // Function to return the count of
    // minimum operations required
    public static int minOperations(int[] a,
                                    int n, int K)
    {
 
        Dictionary map =
                new Dictionary();
 
        for (int i = 0; i < n; i++)
        {
 
            // Check if the initial array
            // already contains an equal pair
            if (map.ContainsKey(a[i]))
                return 0;
 
            map.Add(a[i], true);
        }
 
        // Create new array with AND operations
        int[] b = new int[n];
        for (int i = 0; i < n; i++)
            b[i] = a[i] & K;
 
        // Clear the map
        map.Clear();
 
        // Check if the solution
        // is a single operation
        for (int i = 0; i < n; i++)
        {
 
            // If Bitwise OR operation between
            // 'k' and a[i] gives
            // a number other than a[i]
            if (a[i] != b[i])
                map.Add(b[i], true);
        }
 
        // Check if any of the a[i]
        // gets equal to any other element
        // of the array after the operation
        for (int i = 0; i < n; i++)
        {
 
            // Single operation
            // will be enough
            if (map.ContainsKey(a[i]))
                return 1;
        }
 
        // Clear the map
        map.Clear();
 
        // Check if the solution
        // is two operations
        for (int i = 0; i < n; i++)
        {
 
            // Check if the array 'b'
            // contains duplicates
            if (map.ContainsKey(b[i]))
                return 2;
            map.Add(b[i], true);
        }
 
        // Otherwise it is impossible to
        // create such an array with
        // Bitwise OR operations
        return -1;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int K = 3;
        int[] a = { 1, 2, 3, 7 };
        int n = a.Length;
        Console.WriteLine(minOperations(a, n, K));
    }
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
1

复杂度:O(n)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程