# 找出数组中出现超过1/4的三个数

// ConsoleApplication6.cpp : 定义控制台应用程序的入口点。
//找出数组中出现1/4的三个数

#include "stdafx.h"
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
//数组中有三个数出现超过数组长度1/4，求这三个数
void findMoreThanHNumber(int arr[], int *result,int n){
int count1 = 0, count2 = 0, count3 = 0;
int a=-1, b=-1, c=-1;

for (int i = 0; i < n; i++){
if (arr[i] == a){
count1++;
}
else if (arr[i] == b){
count2++;
}
else if (arr[i] == c){
count3++;
}else if (count1 == 0){
a = arr[i];
count1 = 1;
}
else if (count2 == 0){
b = arr[i];
count2 = 1;

}
else if (count3 == 0){

c = arr[i];
count3 = 1;

}
else{
count1--;
count2--;
count3--;
}

}
//int ans[3] = { a, b, c };
result[0] = a;
result[1] = b;
result[2] = c;

/*for (int i = 0; i < 3; i++){
cout << result[i] << " ";
}*/
}

int _tmain(int argc, _TCHAR* argv[])
{
const int N = 15;
int A[N], i, j, k;
for (i = 0; i<N / 4 + 1; ++i) A[i] = 1;
for (j = 0; j<N / 4 + 1; ++j) A[i + j] = 2;
for (k = 0; k<N / 4 + 1; ++k) A[i + j + k] = 3;
for (k = i + j + k; k<N; ++k) A[k] = k;
random_shuffle(A, A + N);
for (int i = 0; i < N; i++){
cout << A[i] << " ";
}
cout << "The Count of 3 Number more than 1/4 the Array size in:\n";
//Print(A, N);
int X[3];
findMoreThanHNumber(A, X,N);
cout << "\nAnswer 1 = " << X[0] << endl;
cout << "Answer 2 = " << X[1] << endl;
cout << "Answer 3 = " << X[2] << endl;
system("pause");
return 0;
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：找出数组中出现超过1/4的三个数 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)