Java Array Exercises: Get the majority element from a given array of integers containing duplicates
Java Array: Exercise-38 with Solution
Write a Java program to get the majority element from a given array of integers containing duplicates.
Majority element: A majority element is an element that appears more than n/2 times where n is the size of the array.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
// Array - test majority element
int nums[] = { 1, 6, 6, 5, 7, 4, 1, 7, 7, 7, 7, 7, 7, 7, 2 };
System.out.println("Original Array : "+Arrays.toString(nums));
int result = MajorityElement(nums);
if (result != -1)
System.out.println("Majority element is " + result);
else
System.out.println("Majority element does not exist");
}
public static int MajorityElement(int arra1[])
{
int n = arra1.length;
// Hash Map
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Element's frequency in a map
for (int i = 0; i < n; i++)
{
if (map.get(arra1[i]) == null)
map.put(arra1[i], 0);
map.put(arra1[i], map.get(arra1[i]) + 1);
}
// Return the element if its count is more than n/2
Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry)it.next();
if ((int)pair.getValue() > n/2)
return (int)pair.getKey();
it.remove();
}
// no majority element
return -1;
}
}
Sample Output:
Original Array : [1, 6, 6, 5, 7, 4, 1, 7, 7, 7, 7, 7, 7, 7, 2] Majority element is 7
Flowchart:
Visualize Java code execution (Python Tutor):
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to create an array of its anti-diagonals from a given square matrix.
Next: Write a Java program to print all the LEADERS in the array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework