diff --git a/cpp/0169-majority-element.cpp b/cpp/0169-majority-element.cpp index 8a065624a..b8445788e 100644 --- a/cpp/0169-majority-element.cpp +++ b/cpp/0169-majority-element.cpp @@ -7,12 +7,16 @@ The majority element is the element that appears more than ⌊n / 2⌋ times. Yo class Solution { public: int majorityElement(vector& nums) { - unordered_map mp; - int n = nums.size(); - for (int& i : nums){ - if(++mp[i] > n/2) - return i; - } - return -1; + int count = 0; + int res = 0; + + for (const int& num: nums) { + if (count == 0) { + res = num; + } + count += (num == res) ? 1 : -1; + } + + return res; } };