-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajorityElement.java
More file actions
31 lines (25 loc) · 855 Bytes
/
majorityElement.java
File metadata and controls
31 lines (25 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;
import java.util.HashMap;
public class majorityElement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<Integer, Integer> counts = new HashMap<>();
System.out.print("Enter the number of elements in the array: ");
int n = in.nextInt();
System.out.print("Enter the values: ");
int majority = -1;
for (int i = 0; i < n; i++) {
Integer temp = in.nextInt();
counts.get(temp);
counts.putIfAbsent(temp, 0);
int total = counts.get(temp) + 1;
counts.put(temp, total);
if (total > n / 2) {
majority = temp;
break;
}
}
System.out.println("Majority element is: " + majority);
in.close();
}
}