一篇文章告訴你如何尋找水王(數組中存在超過一半的數字)

#include<iostream>
using namespace std;
//case1 排序後返回數組中間的那個數字O nlogn
//case2 hash統計
//case3 順序統計:需要改動數組內容
//case4 消除法:不需要改變數組

int Remove(int a[],int n) 
{
	int candidate = a[0];//候選數
	int count = 1;//出現次數
	for (int i = 1; i < n;i++)
	{
		if (count == 0) 
		{
			candidate = a[i];
			count = 1;
			continue;
		}
		if (a[i] == candidate)
		{
			count++;
		}
		else
			count--;
		
	}
	return candidate;
}

void Swap(int i, int j, int array[])//交換數組內兩個元素
{
	int temp;
	temp = array[i];
	array[i] = array[j];
	array[j] = temp;
}
int Partition(int begin,int end,int a[])
{
	int pivot = a[begin];
	int p = begin + 1;
	int bigger = end;
	while (p<=bigger)
	{
		if (a[p] <= pivot) {
			p++;
		}
		else {
			Swap(p, bigger, a);
			bigger--;
		}
	}
	Swap(begin, bigger, a);
	return bigger;
}
int SelectK(int begin, int end, int k, int a[])
{
	int index = Partition(begin, end, a);//主元下標
	int Kindex = index - begin + 1; //主元是第幾個數
	if (Kindex == k)return a[index];
	if (k < Kindex) return SelectK(begin, index-1, k, a);
	if (k > Kindex) return SelectK(index + 1, end, k - Kindex, a);
}
int main()
{
	int s[] = { 4,4,2,2,4,4,2 };
	cout << "順序統計結果:"<<SelectK(0, 6,(7+1)/2, s);//尋找s數組中第中間小的元素,就是超過一半的那個數字
	//注意偶數直接/2,奇數+1再/2
	cout << endl;
	cout<<"消除法結果:"<<Remove(s,7);
	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章