Majority Element

2017/11/30 posted in  leetcode

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int total = 1;
        int tmp = 1;
        int result = nums[0];
        if (nums.size()==1) {
            return result;
        }
        nums.push_back(INT_MAX); //在最后增加一个边界哨兵
        for (int i=1; i<=nums.size(); i++) {
            if (nums[i]==nums[i-1]) {
                tmp++;
            }else{
                result = tmp>total ? nums[i-1]:result;
                total = max(tmp, total);
                tmp = 1;
            }
        }
        
        return result;
    }
};