leetcode169Majority 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 maxv = nums[0], maxvc = nums[0], maxc = 0, count = 0;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
{
if (maxvc != *it)
{
if (count > maxc)
{
maxv = maxvc;
maxc = count;
}
maxvc = *it;
count = 0;
}
count++;
}
if (count > maxc)
{
maxv = maxvc;
maxc = count;
}
return maxv;
}
};