Answers for "Get the majority element from a given array of integers containing duplicates"

0

Get the majority element from a given array of integers containing duplicates

// check whether `A[i]` is a majority element or not
    for (int i = 0; i <= n/2; i++)
    {
        int count = 1;
        for (int j = i + 1; j < n; j++)
        {
            if (A[j] == A[i]) {
                count++;
            }
        }
 
        if (count > n/2) {
            return A[i];
        }
    }
 
    return -1;
Posted by: Guest on June-29-2021
0

Get the majority element from a given array of integers containing duplicates

public static int findMajorityElement(int[] A)
    {
        // create an empty `HashMap`
        Map<Integer, Integer> map = new HashMap<>();
 
        // store each element's frequency in a map
        for (int i: A) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
 
        // return the element if its count is more than `n/2`
        for (Map.Entry<Integer, Integer> entry: map.entrySet())
        {
            if (entry.getValue() > A.length/2) {
                return entry.getKey();
            }
        }
 
        // no majority element is present
        return -1;
    }
Posted by: Guest on June-29-2021

Code answers related to "Get the majority element from a given array of integers containing duplicates"

Browse Popular Code Answers by Language