find the Majority Element in an array?

There are following way to find the Majority Element in an array in java.

Majority Element :- A Majority Element is an element whose number of occurrences is more than n/2 means half of the size of the input array.

  • First we declare a variable with input array value.
  • Create a HashMap object.
  • Find total number of input array m from array.length method.
  • Traverse through the array from start to end.
  • Take map key from array[i] and value from map.get method with key+1.
  • From map.entrySet we find key and value data.
  • If entry.getValue() data is greater than half the size of the array then find that value from entry.getKey() and store in result variable.
  • Now print the result element.
				
					import java.util.HashMap;
import java.util.Map;

public class MajorityElement {

	public static void main(String[] args) {

		int array[] = { 20, 40, 60, 20, 80, 20, 20, 40, 20, 60, 20 };
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		int m = array.length;
		for (int i = 0; i < m; i++) {
			map.put(array[i], map.getOrDefault(array[i], 0) + 1);
		}
		System.out.println("majority element are :- ");
		for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
			if (entry.getValue() > array.length / 2) {
				int result = entry.getKey();
				System.out.println(result);
			}
		}
	}
}
				
			

Output :-
majority element are :-
20