Created
April 22, 2022 05:14
-
-
Save esase/aa4099e6a44fd0ffe9fdbcd6d82ba4c1 to your computer and use it in GitHub Desktop.
Majority element [https://leetcode.com/problems/majority-element]
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
/** | |
* @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