169. Majority Element(C++)

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.

 

题目大意:

给定一个长度为n的数组,寻找其中的“众数”。众数是指出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的并且数组中的众数永远存在。

 

解题方法:

首先,众数一定大于一半,所以先对数组进行排序,中间元素就是众数。

 

注意事项:

 

C++代码:

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

 

posted @ 2016-05-14 17:49  19Q3  阅读(208)  评论(0编辑  收藏  举报