forked from dimpeshmalviya/JavaBasicPrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElements.java
More file actions
45 lines (34 loc) · 1.19 KB
/
MajorityElements.java
File metadata and controls
45 lines (34 loc) · 1.19 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.*;
public class MajorityElements {
public static void main(String[] args) {
int arr[] = {1,3,2,5,1,3,1,5,1};
int majority1 = Integer.MIN_VALUE, majority2 = Integer.MIN_VALUE , count1 = 0 , count2 = 0;
for(int i=0;i<arr.length;i++){
if(arr[i] == majority1) {
count1++;
} else if(arr[i] == majority2){
count2++;
} else if(count1 == 0){
majority1 = arr[i];
count1 = 1;
} else if(count2 == 0){
majority2 = arr[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0 ;
count2 = 0;
for(int i=0;i<arr.length;i++){
if(arr[i] == majority1) count1++;
if(arr[i] == majority2) count2++;
}
List<Integer> majority = new ArrayList<>();
if(count1 > arr.length/3) majority.add(majority1);
if(count2 > arr.length/3) majority.add(majority2);
majority.forEach(System.out::println);
}
}
//Time complexity of this code is O(N) , Space Complexity is O(1);