如何在数组列表中按前3位排序邮政编码列表



目前,我有一个代表车祸的邮政编码的ArrayList

,

10005
10002
10003
10005
10004

在本例中,我想计算每个邮政编码出现的最高次数,并从高到低排序。我环顾四周,发现很多人都在谈论使用HashMap来实现这一点。不幸的是,我不能按照作业上的说明使用HashMap

在不使用HashMap/Hashtable的情况下,计算每个邮政编码发生的事故次数的最佳方法是什么?

我想过做arrayOfZip[zipCode] = frequency,然后在那里排序,但问题是,声明的数组将在内存中不必要的巨大。

您可以对列表进行排序,然后迭代计算每个邮政编码的运行时间;然后记录3个最长跑步的长度和它们对应的邮政编码。

我认为基于收集频率的方法将是有用的:

int occurrences = Collections.frequency(zip, "xxxxxx");

对列表进行排序,然后:

int counter;
for(int i=0;i<SizeOfList;i+=counter)
//increment counter by no. of times a zipcode occurred to avoid repetation
    {
        counter=1;
        for(j=i+1;j<SizeOfList;++j)
            { 
                if(zipcode[i]==zipcode[j])//checking one zipcode with all next values in list
                    counter++;
            }
        System.out.print("nFrequency of " + zipcode[i] + " is " + counter);
//getting the frequency of that zipcode and printing it(can store it if you want) 
//Next it will jump the loop by value of counter and hence
//the next zipcode inline will come into loop and it will continue till end
    }

这将打印所有唯一邮政编码的频率。您还可以比较计数器并存储频率最高的三个邮政编码。

最新更新