多数投票算法

Majority Voting Algorithm也叫作Moore Voting Algorithm

在一个数组中,元素个数为n(假设最多投票元素存在),输出元素出现次数大于n/2的数

算法思路:1、一个变量cand表示所求的元素,一个变量count统计个数,将count初始化为0.

                  2、在遍历数组的过程上

                      (1)如果count=0,则将count=1,cand=array[I];

                      (2)否则,如果array[I]=cand,将count++,否则count--

代码如下:

class Solution {
public:
	int majorityElement(vector<int>& nums) 
	{
		int cand = -1;
		int count = 0;

		int len = nums.size(); 
		for (int i = 0; i < len; i++)
		{
			if (count == 0)
			{
				count = 1;
				cand = nums[i];
			}
			else if (nums[i] == cand) count++;
			else count--;
		}

		return cand;
	}
};

一种更通用的情况为:

要求输出出现次数为n/k的元素

思路:需要维持一个长度为k-1的候选者数组及统计数组。如果候选者数组没有满,将其加入,相应的统计数计为1,如果在候选数组中出现过,将其计数加1,如果没有出现,将所有的计数减1

代码如下:

class Solution 
{
public:
	vector<int> majorityElement(vector<int>& nums) 
	{
		if (nums.empty()) return{};

		return __majorityElement(nums, 3);
	}

private:
	vector<int> __majorityElement(vector<int>& nums, int k)
	{
		int cnt = k - 1;

		vector<int> candidates(cnt, 0);
		vector<int> count(cnt, 0);

		for (int num : nums)
		{
			bool found = false;
			for (int i = 0; i < cnt; i++)
			{
				if (!count[i] || num == candidates[i])
				{
					count[i]++;
					candidates[i] = num;
					found = true;
					break;
				}
			}

			if (!found)
			{
				for (int i = 0; i < cnt; i++)
				{
					count[i]--;
				}
			}
		}

		for (int i = 0; i < cnt; i++)
		{
			count[i] = 0;
		}

		for (int num : nums)
		{
			for (int i = 0; i < cnt; i++)
			{
				if (num == candidates[i])
				{
					count[i]++;
					break;
				}
			}
		}

		vector<int> ans;
		for (int i = 0; i < cnt; i++)
		{
			if (count[i] > nums.size() / k) ans.push_back(candidates[i]);
		}

		return ans;
	}
};


测试代码如下:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	Solution solver;
	vector<int> nums(1, 1);

	int ans = solver.majorityElement(nums);
	cout << ans << endl;

	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值