给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
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;