Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita7928f5

Browse files
author
Mrinal Chauhan
committed
feat : added find majority element in array using Moore's Voting Algorithm
1 parent55ff0ad commita7928f5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Moore Voting Algorithm to find the majority element in an array
3+
* Majority element is the one that appears more than n/2 times
4+
* geeksforgeeks: https://www.geeksforgeeks.org/boyer-moore-majority-voting-algorithm/
5+
*@param {Array} arr array of integers
6+
*@returns {Number} majority element or null if no majority exists
7+
*/
8+
constMooreVotingAlgorithm=(arr)=>{
9+
letcandidate=null;
10+
letcount=0;
11+
12+
// Phase 1: Finding the candidate
13+
for(letnumofarr){
14+
if(count===0){
15+
candidate=num;
16+
count=1;
17+
}elseif(num===candidate){
18+
count++;
19+
}else{
20+
count--;
21+
}
22+
}
23+
24+
// Phase 2: Validate the candidate
25+
count=0;
26+
for(letnumofarr){
27+
if(num===candidate){
28+
count++;
29+
}
30+
}
31+
32+
returncount>arr.length/2 ?candidate :null;
33+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp