Last active
April 16, 2024 01:01
-
-
Save dalloglio/eadb309f58b1a26aa8a7eecd81c34cef to your computer and use it in GitHub Desktop.
Algorithm to find the majority element in an array in linear time and constant space using the Boyer-Moore Voting algorithm. This algorithm works by keeping track of a candidate majority element and its count. It iterates through the array, updating the candidate and count based on certain conditions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function findMajorityElement(nums) { | |
let candidate = nums[0] | |
let count = 1 | |
for (let i = 1; i < nums.length; i++) { | |
if (count === 0) { | |
candidate = nums[i] | |
count = 1 | |
else if (nums[i] === candidate) { | |
count++ | |
} else { | |
count-- | |
} | |
} | |
return candidate | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment