Skip to content

Commit ef47d2f

Browse files
Merge pull request #202 from shoebxsiddiqui/patch-8
Create BoyerMooreVotingAlgo.java
2 parents 179cc8b + d9c969f commit ef47d2f

1 file changed

Lines changed: 85 additions & 0 deletions

File tree

JAVA/BoyerMooreVotingAlgo.java

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
//Ques. Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
2+
3+
4+
// Basic idea is to use Boyer Moore Voting Algo
5+
// there can be atmost 2 elements in the array which can become maximum element because
6+
// 3*(n/3) = n it is possible that only 3 elements can occir exactly n/3 times in the array
7+
// if any element is appearing more than n/3 times atmost 2 elements can be the maximun element...
8+
9+
// now we will maintain two variables num1 , num 2 to store the value of frequently appearing elements using extended boyer moore algo
10+
11+
class BoyerMooreVotingAlgo {
12+
13+
public static void main(String[] args) {
14+
int[] arr = {1,2,3,3,3,4,4,5,4,3};
15+
System.out.println(majorityElement(arr).toString());
16+
}
17+
18+
public static List<Integer> majorityElement(int[] nums) {
19+
List<Integer> list = new ArrayList<>();
20+
if(nums == null) return list;
21+
int num1=0;
22+
int num2=0;
23+
int count1=0;
24+
int count2=0;
25+
for(int i=0;i<nums.length;i++){
26+
int num3 = nums[i];
27+
if(count1>0 && count2>0){
28+
29+
if(num3 == num1){
30+
count1++;
31+
}else if(num3 ==num2){
32+
count2++;
33+
}else{
34+
count1--;
35+
count2--;
36+
}
37+
38+
}else if(count1 >0){
39+
40+
if(num3 == num1){
41+
count1++;
42+
}else{
43+
num2 = num3;
44+
count2++;
45+
}
46+
47+
}else if(count2>0){
48+
49+
if(num3 == num2){
50+
count2++;
51+
}else{
52+
num1 = num3;
53+
count1++;
54+
}
55+
56+
}else{
57+
num1 = num3;
58+
count1++;
59+
}
60+
}
61+
62+
// now we have the values that appears frequently in the array but it doesnot means that they both are maximum elements .........
63+
// so we have to iterate again over the array to cehck for maximum element out of both .......
64+
65+
count1=0;
66+
count2=0;
67+
68+
for(int i=0;i<nums.length;i++){
69+
if(nums[i] == num1){
70+
count1++;
71+
}
72+
else if(nums[i] ==num2){
73+
count2++;
74+
}
75+
}
76+
if(count1>nums.length/3){
77+
list.add(num1);
78+
}
79+
if(count2>nums.length/3){
80+
list.add(num2);
81+
}
82+
83+
return list;
84+
}
85+
}

0 commit comments

Comments
 (0)