多数投票算法

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& 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 majorityElement(vector& nums) 
	{
		if (nums.empty()) return{};

		return __majorityElement(nums, 3);
	}

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

		vector candidates(cnt, 0);
		vector 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 ans;
		for (int i = 0; i < cnt; i++)
		{
			if (count[i] > nums.size() / k) ans.push_back(candidates[i]);
		}

		return ans;
	}
};


测试代码如下:

#include 
#include 

using namespace std;

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

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

	return 0;
}


你可能感兴趣的:(算法笔记)