|
发表于 2020-6-1 19:31:31
|
显示全部楼层
i dont know that whether i did is greedy algorithm ,but maybe it can dislove your problem
#include<iostream>
#include<cstdio>
using namespace std;
int func(int a[],int n,int hash[],int &i,int &imax){
if(n==1){
imax=0;
i=a[0];
hash[a[0]]=1;
return 1;
}else{
int k=-1;
k=func(a,n-1,hash,i,imax);
++hash[a[n-1]];//把当前的值压入哈希,判断上一层传递过来的次数与当前次数比较
if(hash[a[n-1]]>k){//当前层大于上一层的最多次数 ,更新imax,返回次数
imax=n-1;
return hash[a[n-1]];
}else if(hash[a[n-1]==k]){//次数一样时
if(a[n-1]<a[imax]){
imax=n-1;//更新
return hash[a[n-1]];//返回最多次数
}
}
}
}
int main(){
int n=6,i=-1,imax=-1;
int hash[6]={0};
int a[6]={1,2,2,2,1,1};
func(a,6,hash,i,imax);
cout<<a[imax]<<endl;
}
|
|