Skip to content

Instantly share code, notes, and snippets.

@esase
Created April 22, 2022 05:14
Show Gist options
  • Save esase/aa4099e6a44fd0ffe9fdbcd6d82ba4c1 to your computer and use it in GitHub Desktop.
Save esase/aa4099e6a44fd0ffe9fdbcd6d82ba4c1 to your computer and use it in GitHub Desktop.
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let occurrences = 1;
let majorityNumber = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] === majorityNumber) {
occurrences++;
continue;
}
occurrences--;
if (!occurrences) {
occurrences = 1;
majorityNumber = nums[i];
}
}
return majorityNumber;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment