Solving Leetcode’s Majority Element Problem in JavaScript

Return the majority element of an array, which is the element that appears more than ⌊ n/2 ⌋ times.
  • In order to know which element shows up the most, we’re going to have to iterate through the entire array. There’s just no way around this.
  • We’re going to have to figure out a way count how many of each element there is and refer back to this count later in order to know which one is the most frequent flyer in our array.
function majorityElement(nums) {
let numsObj = {};
let maxFreq = 0;
}
numsObj = {
2: 1,
3: 2
}
for (num in numsObj) {
if (numsObj[num] > maxFreq) {
maxFreq = numsObj[num];
maxElement = parseInt(num);
}
}
function majorityElement(nums) {
let numsObj = {};
let maxFreq = 0;
let maxElement = null;
for (let num of nums) {
numsObj[num] = numsObj[num] + 1 || 1;
}
for (num in numsObj) {
if (numsObj[num] > maxFreq) {
maxFreq = numsObj[num];
maxElement = parseInt(num);
}
}
return maxElement;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store