Majority of Elements
During my daily Leetcode challenge I ran into an interesting problem, the Majority of elements. I was required to take the most frequent number in the array. The question states, “Given an array nums of size n, return the majority element”. For example, given an array of integers that is repeated frequently, return the integer that appears the most.
function majorityElement(num){}console.log(majorityElement([2,2,1,1,1,2,2]))
Since it's the majority we can find it through the center which will reveal the majority. The Aha moment I found was if the numbers were sorted from small to greatest the majority integer will eventually land in the middle. Therefore I used the sorting technique in this problem.
function majorityElement(num){num.sort((a,b) => a - b)}
I would then sum up the length of the array to determine where the majority of numbers were if divided evenly. If it was divided evenly I would return the length divided by 2 to access the majority number Here’s a closer look below.
function majorityElement(num){num.sort((a,b) => a - b)let total = num.lengthif(total % 2 === 0){
return num[total / 2]
}}
Otherwise, If the length had a remainder and did not divide evenly I would subtract 1 from the length and divide by 2 to access the frequent number. Here is a closer look below.
function majorityElement(num){num.sort((a,b) => a - b)let total = num.lengthif(total % 2 === 0){
return num[total / 2]
} else {
return num[(total - 1) / 2]
}}console.log(majorityElement([2,2,1,1,1,2,2]))
Thanks for reading till next time coders.