zhangchuan的博客

随便写写,权当知识点总结

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

原题:已知数组中有三个数超过了数组长度的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;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChengNuoDeYongYuan/article/details/52372155
个人分类: 数据结构与算法
上一篇后缀树
下一篇二叉搜索树转换为双向链表
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭