#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;
}
一篇文章告诉你如何寻找水王(数组中存在超过一半的数字)
最新推荐文章于 2023-09-14 20:41:46 发布