给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
样例
给出数组[1,1,1,1,2,2,2],返回 1
挑战
要求时间复杂度为O(n),空间复杂度为O(1)
这道题也是用贪心算法,把数组里的元素看为两种一种是主元素另一种是其他元素,当是主元素时count加一,若非主元素count减一,若count = 0则交换主元素。
一开始平这样的代码也通过了,但后来在整理这篇博客时发现lintcode有bug如果是1 1 1 2 3 4这样的数据我的代码还是会返回1,但1 并没有超过总数的1/2,所以还要加一个count < 1的判断。
代码
int majorityNumber(vector<int> &nums) {
// write your code here
int length = nums.size() ;
int i;
int count = 0;
//int biao = nums[0];
int result = 0;
for(i = 0;i < length ;i++)
{
if(count == 0)
{
result = nums[i];
count = 1;
}
else
{
if(result == nums[i])
{
count ++;
}
else
{
count --;
}
}
}
if(count < 1)
{
result = 0;
}
return result;
本文介绍了一种用于查找数组中主元素的贪心算法,该元素出现次数超过数组长度的一半。文章提供了具体实现代码,并强调了算法的时间复杂度为O(n)及空间复杂度为O(1)。
1307

被折叠的 条评论
为什么被折叠?



