majority element

mail@pastecode.io avatar
unknown
c_cpp
24 days ago
475 B
3
Indexable
Never
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        int cnt = 1, major = nums.size() / 2, ans = nums[0];

        for (int i = 1; i < nums.size(); i++)
        {
            if (nums[i] == nums[i - 1]) cnt++;
            else cnt = 1;

            if (cnt > major) 
            {
                ans = nums[i];
                break;
            }
        }

        return ans;
    }
};
Leave a Comment