📜  计算矩阵中的多数元素

📅  最后修改于: 2021-10-27 06:55:02             🧑  作者: Mango

给定包含重复元素的 NxM 整数矩阵。任务是找到给定矩阵中所有出现多数的元素的计数,其中多数元素是那些频率大于或等于 (N*M)/2 的元素。
例子

Input : mat[] = {{1, 1, 2},
                {2, 3, 3},
                {4, 3, 3}}
Output : 1
The majority elements is 3 and, its frequency is 4.

Input : mat[] = {{20, 20},
                 {40, 40}}
Output : 2

方法

  • 遍历矩阵并使用C++中的map来存储矩阵元素的频率,使得map的key是矩阵元素,value是它在矩阵中的频率。
  • 然后,遍历map,找到带有count变量的元素出现的频率,对多数元素进行计数,并检查是否等于或大于(N*M)/2。如果为真,则增加计数。

下面是上述方法的实现:

C++
// C++ program to find count of all
// majority elements in a Matrix
 
#include 
using namespace std;
 
#define N 3 // Rows
#define M 3 // Columns
 
// Function to find count of all
// majority elements in a Matrix
int majorityInMatrix(int arr[N][M])
{
 
    unordered_map mp;
 
    // Store frequency of elements
    // in matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            mp[arr[i][j]]++;
        }
    }
 
    // loop to iteratre through map   
    int countMajority = 0;
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {
 
        // check if frequency is greater than
        // or equal to (N*M)/2
        if (itr->second >= ((N * M) / 2)) {
            countMajority++;
        }
    }
 
    return countMajority;
}
 
// Driver Code
int main()
{
 
    int mat[N][M] = { { 1, 2, 2 },
                      { 1, 3, 2 },
                      { 1, 2, 6 } };
 
    cout << majorityInMatrix(mat) << endl;
 
    return 0;
}


Java
// Java program to find count of all
// majority elements in a Matrix
import java.util.*;
 
class GFG
{
    static int N = 3; // Rows
    static int M = 3; // Columns
     
    // Function to find count of all
    // majority elements in a Matrix
    static int majorityInMatrix(int arr[][])
    {
     
        HashMap mp =
                new HashMap();
     
        // Store frequency of elements
        // in matrix
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if(mp.containsKey(arr[i][j]))
                    mp.put(arr[i][j], mp.get(arr[i][j]) + 1 );
                else
                    mp.put(arr[i][j], 1);
            }
        }
     
        // loop to iteratre through map
        int countMajority = 0;
         
        Iterator> itr =
                                mp.entrySet().iterator();
         
        while(itr.hasNext())
        {
            // check if frequency is greater than
            // or equal to (N*M)/2
            HashMap.Entry entry = itr.next();
             
            if (entry.getValue() >= ((N * M) / 2))
            {
                countMajority++;
            }
        }
     
        return countMajority;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
     
        int mat[][] = { { 1, 2, 2 },
                        { 1, 3, 2 },
                        { 1, 2, 6 } };
     
        System.out.println(majorityInMatrix(mat));
    }
}
 
// This code is contributed by ihritik


Python3
# Python 3 program to find count of all
# majority elements in a Matrix
N = 3 # Rows
M = 3 # Columns
 
# Function to find count of all
# majority elements in a Matrix
def majorityInMatrix(arr):
     
    # we take length equal to max
    # value in array
    mp = {i:0 for i in range(7)}
 
    # Store frequency of elements
    # in matrix
    for i in range(len(arr)):
        for j in range(len(arr)):
            mp[arr[i][j]] += 1
     
    # loop to iteratre through map
    countMajority = 0
    for key, value in mp.items():
         
        # check if frequency is greater than
        # or equal to (N*M)/2
        if (value >= (int((N * M) / 2))):
            countMajority += 1
     
    return countMajority
 
# Driver Code
if __name__ == '__main__':
    mat = [[1, 2, 2],
           [1, 3, 2],
           [1, 2, 6]]
    print(majorityInMatrix(mat))
 
# This code is contributed by
# Shashank_Sharma


C#
// C# program to find count of all
// majority elements in a Matrix
using System;
using System.Collections.Generic;
 
class GFG
{
    static int N = 3; // Rows
    static int M = 3; // Columns
     
    // Function to find count of all
    // majority elements in a Matrix
    static int majorityInMatrix(int [ , ]arr)
    {
     
        Dictionary mp =
                new Dictionary();
     
        // Store frequency of elements
        // in matrix
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if(mp.ContainsKey(arr[i, j]))
                    mp[arr[i, j]]++;
                else
                    mp[arr[i, j]] = 1;
            }
        }
     
        // loop to iteratre through map
        int countMajority = 0;
        Dictionary.KeyCollection keyColl =
                                            mp.Keys;
         
        foreach( int i in keyColl)
        {    
            // check if frequency is greater than
            // or equal to (N*M)/2
             
            if ( mp[i] >= ((N * M) / 2))
            {
                countMajority++;
            }
        }
     
        return countMajority;
    }
     
    // Driver Code
    public static void Main ()
    {
     
        int [, ] mat = { { 1, 2, 2 },
                        { 1, 3, 2 },
                        { 1, 2, 6 } };
     
        Console.WriteLine(majorityInMatrix(mat));
    }
}
 
// This code is contributed by ihritik


Javascript


输出:

1

时间复杂度: O(N x M)
辅助空间: O(NXM)
进一步优化:
我们可以使用摩尔投票算法在 O(1) 额外空间中解决上述问题。我们可以简单地将矩阵元素视为一维数组。

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