您的位置:首页 > 其它

LeetCode(169)Majority Element

2015-08-15 20:47 525 查看

题目

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

分析

给定一个整数序列,求出其中出现次数大于floor(n/2)的元素,并返回。

这是一个很简单的题目,首先将序列排序,得到一个有序排列,然后依次遍历,统计重复元素的出现次数,返回次数大于一半的元素即可。

AC代码

class Solution {
public:
int majorityElement(vector<int>& nums) {
//题目假设输入数组非空,且出现次数大于[n/2]的元素存在
int len = nums.size() , count = len/2;

sort(nums.begin(), nums.end());

if (len == 1)
return nums[0];
int tmp = 1;
for (int i = 0; i < len-1; i++)
{
if (nums[i + 1] == nums[i])
{
++tmp;
if (tmp > count)
return nums[i];
}
else{
tmp = 1;
}//if
}//for
return -1;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: