[leetcode] 169. Majority Element

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 i=0;
        for(i=0;i<(nums.size()/2+1);i++)
        {
            if(nums[i]==nums[i+nums.size()/2]) return nums[i];
        }
    }
};

前提:majority element存在。

先排序,再比较nums[i]和nums[i+nums.size()/2]是不是一样

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