Majority Element_LeetCode

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.

 

解题思路:

(方法一):利用vector自带的函数sort()对整个数组进行排序,下标为第n/2的元素必定是出现次数超过 ⌊ n/2 ⌋ 次的数。

 

代码:

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

 

posted @ 2017-09-28 17:39  SYSU_Bango  阅读(90)  评论(0)    收藏  举报