169.[LeetCode]Majority Element

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        int n = nums.size(),count(1);
        for(int i=0;i<n;i++){
            if(nums[i+1] != nums[i]) {
                if(count > n/2) {
                    count = i;
                    break;
                } else {
                    count = 1;
                }
            }
            else {
                count++;
            }
        }
        return nums[count];
    }
};

你可能感兴趣的:(169.[LeetCode]Majority Element)