取出整型数据中出现次数最多的元素,并按照升序排列返回。
要求实现方法:
public static int[] calcTimes(int[] num, int len);
【输入】 num:整型数组;
len 输入的整数个数
【返回】 按照升序排列返回整型数组中出现次数最多的元素
【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出
示例
输入:num = {1,1,3,4,4,4,9,9,9,10} len = 10
返回:{4,9}
这是我用 c++编写的代码
#include
#include
using namespace std;
/*
在数组arr_num中查找 num,如果有,将对应的arr_count 加1,如果没有,在arr_num中添加,
设置arr_count 设置为1,并且相应的计数器加1;
*/
void find (int & num_,int *arr_num,int *arr_count,int &count)
{
for(int j =0 ;j <count ;j++)
if(arr_num[j] == num_)
arr_count[j]++;
arr_num[count] = num_;
arr_count[count]= 1;
count++;
}
int calcTimes (int num ,int len)
{
if (len == 0)
return 0;
int count = 0,dex =0 ;
//创建两个数字,一个用来存放数字,一个用来存放该数字出现的次数
int *arr_count = new int[len];
int *arr_num = new int [len];
for(dex =0 ;dex <len ;dex++)
find (num[dex],arr_num,arr_count,count);
int max = -1;
int numb ;
//arr_cout出现的最大值,该最大值出现的次数。
for(dex = 0 ;dex < count ;dex++)
if(max < arr_count[dex])
{
max = arr_count[dex];
numb =1;
}
else
if(max == arr_count[dex] )
numb++;
int *out_out = new int [numb];
int i = 0;
//将出现次数最多的赋值给另外一个数组。
for(dex = 0 ;dex < count ;dex++)
if (arr_count[dex] == max)
{
out_out[i] = arr_num[dex];
i++;
}
delete [] arr_count;
delete [] arr_num;
//对出现次数最多的数字进行排序
sort(out_out,out_out+numb);
//自己检验下
for(int jj =0 ;jj<numb;jj++)
cout<<out_out[jj]<<" "<<jj<<endl;
return out_out;
}
int main()
{
int num[] = {1,1,3,4,4,4,9,9,9,10}, len = 10;
int * out = calcTimes(num,len);
//这边该如何 sizeof (out) 是一个指针的长度,它不能用来判断数组的个数
int n = sizeof(out)/sizeof(int);
for(int i =0 ;i<n ;i++)
cout<<out[i]<<ends;
cout<<endl;
}
最后输出的时候,出现问题,不知道是最后sizeof(out)/size(int)出错,还是没有按照要求pbulic static int [] calcTimes()写,我对这个public static 不太了解 还是这本来就是java中的,不是C++的?