leetcode-169-majority element

Problem Description:
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.

题目大意:

给一个数组,里面有一个元素出现了至少⌊ n/2 ⌋次,找到这个元素。

Solutions:

排序以后中间的那个元素肯定是所求元素。

Code in C++:

class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            sort(nums.begin(),nums.end());
            return nums[nums.size()/2];
        }
};