169. Majority Element

原文题目:

169. Majority Element

读题:

这个是一道经典算法题,可以用摩尔投票算法(Moore voting algorithm),前提是一定有一个元素的个数超过总元素个数的一半。

比如对于序列[1,1,1,1,1,1,2,2,3,3,4],此时设置一个count,由于前6个都相等为1,count的值累加依次是1,2,3,4,5,6,从第七个数开始就不等于1了,此时count开始减一,值为5,4,3,2,1,由于减的过程count的值不为0,因此一直减,遍历完后count还是不为0,表明第一个值就是所要寻找的主元素。

class Solution 
{
public:
	int majorityElement(vector<int>& nums) 
	{
		int curIdx = 0;
		int count = 1;
		int i= 1;
		for(i = 1;i< nums.size();++i)
		{
			nums[i] == nums[curIdx]? ++count : --count;
			if(!count)
			{
				curIdx = i;
				count = 1;
			}
		}
		return nums[curIdx];
	}
};
int main()
{
	Solution s;
	vector <int> nums;
	int result;
	int i = 0;
	/*for(i = 0;i < 6;i++)
	{
		nums.push_back(5);
	}*/
	nums.push_back(7);
	nums.push_back(8);
	nums.push_back(5);
	nums.push_back(5);
	nums.push_back(5);

	
	result = s.majorityElement(nums);
	cout << result<<endl;
}
if __name__ == '__main__':
    L =[1,2,1,1,1,1,1,2,3,3,4]
    count = 0
    major = L[0]
    for i in range(1,len(L)):
        if L[i] == major:
            count += 1
        else:
            count -=1
        if not count:
            major = L[i]
            count = 1
    print(major)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值